graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat: SDK orchestration layer with token budgets and journaled resume (#276)
Rach Pradhanb04ae0242818
diff --git a/bun.lock b/bun.lockindex f4d55ebd..6f937279 100644--- a/bun.lock+++ b/bun.lock@@ -7,7 +7,7 @@},"gui": {"name": "codegraff-gui",- "version": "0.0.162",+ "version": "0.0.166","dependencies": {"@base-ui/react": "^1.4.0","@codegraff/diffs": "workspace:*",@@ -75,6 +75,15 @@"react-dom",],},+ "sdk/ts": {+ "name": "@codegraff/sdk",+ "version": "0.3.1",+ "devDependencies": {+ "@types/node": "^22.10.2",+ "bun-types": "^1.3.11",+ "typescript": "~5.9.3",+ },+ },},"packages": {"@antfu/install-pkg": ["@antfu/[email protected]", "", { "dependencies": { "package-manager-detector": "^1.3.0", "tinyexec": "^1.0.1" } }, "sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ=="],@@ -147,6 +156,8 @@"@codegraff/diffs": ["@codegraff/diffs@workspace:packages/diffs"],+ "@codegraff/sdk": ["@codegraff/sdk@workspace:sdk/ts"],+"@dotenvx/dotenvx": ["@dotenvx/[email protected]", "", { "dependencies": { "commander": "^11.1.0", "conf": "^10.2.0", "dotenv": "^17.2.1", "eciesjs": "^0.4.10", "enquirer": "^2.4.1", "env-paths": "^2.2.1", "execa": "^5.1.1", "fdir": "^6.2.0", "ignore": "^5.3.0", "object-treeify": "1.1.33", "open": "^8.4.2", "picomatch": "^4.0.4", "systeminformation": "^5.22.11", "undici": "^7.11.0", "which": "^4.0.0", "yocto-spinner": "^1.1.0" }, "bin": { "dotenvx": "src/cli/dotenvx.js" } }, "sha512-AWf8edAsSpINqJbtaZsaiV3PO+vw5pS4wJFl6ahYNdnp3gfFYeMxRCdsA9042bKP4UPCs8yr5FikSFlvkmFVag=="],"@ecies/ciphers": ["@ecies/[email protected]", "", { "peerDependencies": { "@noble/ciphers": "^1.0.0" } }, "sha512-patgsRPKGkhhoBjETV4XxD0En4ui5fbX0hzayqI3M8tvNMGUoUvmyYAIWwlxBc1KX5cturfqByYdj5bYGRpN9g=="],@@ -489,7 +500,7 @@"@types/json-schema": ["@types/[email protected]", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],- "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-fRa09kZTgu8o71KFcDjUFuc7F+dEbZYZmkI0mg5YBTRs0yMKjYHsq/c0urDKeDb+D5qVgXOdFcuu+DZPKOITwA=="],+ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q=="],"@types/q": ["@types/[email protected]", "", {}, "sha512-hroOstUScF6zhIi+5+x0dzqrHA1EJi+Irri6b1fxolMTqqHIV/Cg77EtnQcZqZCu8hR3mX2BzIxN4/GzI68Kfw=="],@@ -1463,7 +1474,7 @@"undici": ["[email protected]", "", {}, "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA=="],- "undici-types": ["[email protected]", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],+ "undici-types": ["[email protected]", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],"unicorn-magic": ["[email protected]", "", {}, "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA=="],@@ -1529,6 +1540,8 @@"zustand": ["[email protected]", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-/8tAspM5LMPr28b3fwLYrtdj77ECpfZviaP75CMTnwO8ISyaE4GDIG/9rDDYq/cH9D2Xw2A2RXglLInmVBQB/g=="],+ "@codegraff/sdk/typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],+"@dotenvx/dotenvx/commander": ["[email protected]", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="],"@dotenvx/dotenvx/execa": ["[email protected]", "", { "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^6.0.0", "human-signals": "^2.1.0", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.1", "onetime": "^5.1.2", "signal-exit": "^3.0.3", "strip-final-newline": "^2.0.0" } }, "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg=="],@@ -1571,8 +1584,12 @@"body-parser/iconv-lite": ["[email protected]", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],+ "bun-types/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-fRa09kZTgu8o71KFcDjUFuc7F+dEbZYZmkI0mg5YBTRs0yMKjYHsq/c0urDKeDb+D5qVgXOdFcuu+DZPKOITwA=="],+"coa/chalk": ["[email protected]", "", { "dependencies": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", "supports-color": "^5.3.0" } }, "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ=="],+ "codegraff-gui/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-fRa09kZTgu8o71KFcDjUFuc7F+dEbZYZmkI0mg5YBTRs0yMKjYHsq/c0urDKeDb+D5qVgXOdFcuu+DZPKOITwA=="],+"conf/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],"conf/ajv-formats": ["[email protected]", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA=="],@@ -1659,12 +1676,16 @@"ajv-formats/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],+ "bun-types/@types/node/undici-types": ["[email protected]", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],+"coa/chalk/ansi-styles": ["[email protected]", "", { "dependencies": { "color-convert": "^1.9.0" } }, "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA=="],"coa/chalk/escape-string-regexp": ["[email protected]", "", {}, "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg=="],"coa/chalk/supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^3.0.0" } }, "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow=="],+ "codegraff-gui/@types/node/undici-types": ["[email protected]", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],+"conf/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],"csso/css-tree/mdn-data": ["[email protected]", "", {}, "sha512-dn6wd0uw5GsdswPFfsgMp5NSB0/aDe6fK94YJV/AJDYXL6HVLWBsxeq7js7Ad+mU2K9LAlwpk6kN2D5mwCPVow=="],diff --git a/package.json b/package.jsonindex aa07df89..0fe82fdf 100644--- a/package.json+++ b/package.json@@ -4,6 +4,7 @@"packageManager": "[email protected]","workspaces": ["gui",- "packages/*"+ "packages/*",+ "sdk/ts"]}diff --git a/sdk/generate.py b/sdk/generate.pyindex 6ec4863d..a673cd58 100644--- a/sdk/generate.py+++ b/sdk/generate.py@@ -83,6 +83,7 @@ export type Event =| {{ type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }}| {{ type: "tool_result"; name: string; is_error: boolean; text: string }}| {{ type: "tool_call_finished"; name: string; is_error: boolean; ms: number }}+ | {{ type: "agent_usage"; id: string; ok: boolean; duration_ms: number; tool_calls: number; context_tokens: number; cache_read_tokens: number }}| {{ type: "finalizing" }}| {{ type: "turn"; text: string; context_tokens: number; cost_usd: number; complete?: boolean; metadata_complete?: boolean }}| {{ type: "system_prompt"; ok: boolean; append: boolean; chars: number }}@@ -519,6 +520,7 @@ export type Event =| {{ type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }}| {{ type: "tool_result"; name: string; is_error: boolean; text: string }}| {{ type: "tool_call_finished"; name: string; is_error: boolean; ms: number }}+ | {{ type: "agent_usage"; id: string; ok: boolean; duration_ms: number; tool_calls: number; context_tokens: number; cache_read_tokens: number }}| {{ type: "finalizing" }}| {{ type: "turn"; text: string; context_tokens: number; cost_usd: number; complete?: boolean; metadata_complete?: boolean }}| {{ type: "system_prompt"; ok: boolean; append: boolean; chars: number }}diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.pyindex 34e84aaa..2e650210 100644--- a/sdk/py/harness_sdk.py+++ b/sdk/py/harness_sdk.py@@ -14,7 +14,7 @@ import urllib.requestfrom typing import Iterator, OptionalMODELS = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"]-TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "learn_candidate"]+TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate"]PROVIDERS = ["anthropic", "codegraff", "deepseek", "openai", "minimax", "xiaomi", "kimi", "moonshot", "xai", "zai", "fugu", "fireworks", "mlx", "lmstudio", "codex"]diff --git a/sdk/ts/README.md b/sdk/ts/README.mdindex e1bc62cb..8c4f92ac 100644--- a/sdk/ts/README.md+++ b/sdk/ts/README.md@@ -76,6 +76,54 @@ console.log(await h.ask("what files are here?"));await h.close();```+## Orchestration (#276): agent()/parallel()/pipeline(), budgets, resumable runs++`@codegraff/sdk/orchestrate` is a deterministic scripting layer on top of the+harness's `subagent`/`workflow` tools/`agent_output` — instead of asking the+root model to decide, on its own judgement, to fan out, the SDK drives those+tools programmatically:++```ts+import { agent, parallel, pipeline, Run } from "@codegraff/sdk/orchestrate";++// one subagent call+const r = await agent("summarize README.md", { agent: "researcher" });+console.log(r.ok, r.text, r.usage.contextTokens);++// parallel(): explicit barrier, a failed thunk resolves null (never rejects)+const reviews = await parallel([+ () => agent("review auth.ts for bugs", { agent: "reviewer" }),+ () => agent("review db.ts for bugs", { agent: "reviewer" }),+]);++// pipeline(): per-item flow, no barrier between an item's stages -- one+// slow file never blocks another file's later stages+const results = await pipeline(+ ["a.ts", "b.ts"],+ async (_prev, file) => agent(`refactor ${file}`, { isolation: "worktree" }),+ async (prev, file) => agent(`review this diff for ${file}:\n${(prev as any).text}`),+);+```++A `Run` adds a token-aware budget and a JSONL journal + prefix-resume so a+re-invoked script skips unchanged calls and goes live from the first+divergence:++```ts+const run = new Run({ budget: { maxTokens: 200_000 } });+await run.agent("step one");+await run.agent("step two");+console.log(run.budget.spent(), run.budget.remaining());++// later / after a crash: replay unchanged calls, run only what diverged+const resumed = new Run({ resumeFrom: run.journalPath });+await resumed.agent("step one"); // cached, no process spawned+```++See `orchestrate.ts`'s file header for the exact journal format and the+concurrency/determinism guarantees (and their documented edges) for+`parallel()`/`pipeline()`.+## Links- Repository: <https://github.com/justrach/codegraff>diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.tsindex b102b6e3..1bc0c31a 100644--- a/sdk/ts/harness.ts+++ b/sdk/ts/harness.ts@@ -8,10 +8,10 @@ import { homedir } from "node:os";import { join } from "node:path";import { createInterface } from "node:readline";-export const HARNESS_VERSION = "0.6";+export const HARNESS_VERSION = "0.8";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow" | "learn_candidate";+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate";export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";/** Events streamed by `harness --json` (one JSON object per stdout line), each@@ -32,6 +32,7 @@ export type Event =| { type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }| { type: "tool_result"; name: string; is_error: boolean; text: string }| { type: "tool_call_finished"; name: string; is_error: boolean; ms: number }+ | { type: "agent_usage"; id: string; ok: boolean; duration_ms: number; tool_calls: number; context_tokens: number; cache_read_tokens: number }| { type: "finalizing" }| { type: "turn"; text: string; context_tokens: number; cost_usd: number; complete?: boolean; metadata_complete?: boolean }| { type: "system_prompt"; ok: boolean; append: boolean; chars: number }@@ -418,4 +419,4 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<Event> {}export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"];-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "learn_candidate"];+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate"];diff --git a/sdk/ts/orchestrate.test.ts b/sdk/ts/orchestrate.test.tsnew file mode 100644index 00000000..c2072bed--- /dev/null+++ b/sdk/ts/orchestrate.test.ts@@ -0,0 +1,342 @@+// Tests for orchestrate.ts (#276 P0-2). Everything here runs against a+// FakeRunner — no live `graff` process, no API keys, no network — since the+// thing under test is the orchestration logic (concurrency/barriers/+// budget/journal), not the transport (HarnessRunner, which needs a real+// 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 { tmpdir } from "node:os";+import { join } from "node:path";+import {+ agent,+ Budget,+ DEFAULT_CONCURRENCY,+ parallel,+ parseBackgroundId,+ pipeline,+ Run,+ subagentToolInput,+ type AgentResult,+ type AgentRunner,+ type AgentUsage,+ type Stage,+ type SubagentSpec,+} from "./orchestrate.ts";++const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));++function usage(contextTokens = 0): AgentUsage {+ return { durationMs: 1, toolCalls: 1, contextTokens, cacheReadTokens: 0 };+}++function ok(text: string, contextTokens = 0): AgentResult {+ return { ok: true, text, usage: usage(contextTokens), cached: false };+}++/** Deterministic, in-process stand-in for HarnessRunner. */+class FakeRunner implements AgentRunner {+ calls: SubagentSpec[] = [];+ constructor(private impl: (spec: SubagentSpec, callIndex: number) => Promise<AgentResult> | AgentResult) {}+ async run(spec: SubagentSpec): Promise<AgentResult> {+ const n = this.calls.length;+ this.calls.push(spec);+ return this.impl(spec, n);+ }+}++function tmpJournalDir(): string {+ return mkdtempSync(join(tmpdir(), "graff-journal-"));+}++// ── parallel(): explicit barrier, null-on-failure ───────────────────────++describe("parallel()", () => {+ test("explicit barrier — resolves only once the slowest thunk settles", async () => {+ let fastDone = false;+ let slowDone = false;+ const thunks = [+ async () => {+ await sleep(5);+ fastDone = true;+ return "fast";+ },+ async () => {+ await sleep(45);+ slowDone = true;+ return "slow";+ },+ ];+ const pending = parallel(thunks);+ await sleep(20);+ expect(fastDone).toBe(true);+ expect(slowDone).toBe(false); // still in flight -- parallel() has not returned+ const results = await pending;+ expect(slowDone).toBe(true);+ expect(results).toEqual(["fast", "slow"]);+ });++ test("a failed thunk resolves null, never rejects the batch", async () => {+ const results = await parallel([+ async () => "ok-1",+ async () => {+ throw new Error("boom");+ },+ async () => "ok-3",+ ]);+ expect(results).toEqual(["ok-1", null, "ok-3"]);+ });++ test("respects the concurrency cap", async () => {+ let active = 0;+ let maxActive = 0;+ const thunks = Array.from({ length: 6 }, () => async () => {+ active++;+ maxActive = Math.max(maxActive, active);+ await sleep(10);+ active--;+ return true;+ });+ await parallel(thunks, { concurrency: 2 });+ expect(maxActive).toBeLessThanOrEqual(2);+ });++ test("default concurrency matches the core's background-agent cap (8)", () => {+ expect(DEFAULT_CONCURRENCY).toBe(8);+ });+});++// ── pipeline(): per-item flow, no cross-stage barrier ────────────────────++describe("pipeline()", () => {+ test("no-barrier proof: a slow item does not block another item's later stages", async () => {+ const order: string[] = [];+ const stage1: Stage<string> = async (_prev, item) => {+ await sleep(item === "slow" ? 60 : 5);+ order.push(`${item}:stage1`);+ return item;+ };+ const stage2: Stage<string> = async (_prev, item) => {+ order.push(`${item}:stage2`);+ return item;+ };+ const results = await pipeline(["slow", "fast"], stage1, stage2);+ expect(results).toEqual(["slow", "fast"]);+ // "fast"'s whole chain finishes before "slow" even clears stage 1 --+ // proof there is no barrier between items at a stage boundary.+ expect(order.indexOf("fast:stage2")).toBeLessThan(order.indexOf("slow:stage1"));+ });++ test("stage callbacks receive (prevResult, originalItem, index)", async () => {+ const seen: Array<[unknown, string, number]> = [];+ const stage1: Stage<string> = async (prev, item, index) => {+ seen.push([prev, item, index]);+ return item.toUpperCase();+ };+ const stage2: Stage<string> = async (prev, item, index) => {+ seen.push([prev, item, index]);+ return `${prev}!`;+ };+ const results = await pipeline(["a", "b"], stage1, stage2);+ expect(results).toEqual(["A!", "B!"]);+ expect(seen).toEqual([+ [undefined, "a", 0],+ [undefined, "b", 1],+ ["A", "a", 0],+ ["B", "b", 1],+ ]);+ });++ test("a failing stage resolves that item null without aborting the others", async () => {+ const results = await pipeline(["a", "b"], async (_prev, item) => {+ if (item === "a") throw new Error("bad a");+ return item.toUpperCase();+ });+ expect(results).toEqual([null, "B"]);+ });+});++// ── Budget ────────────────────────────────────────────────────────────────++describe("Budget", () => {+ test("spent()/remaining()/total arithmetic", () => {+ const b = new Budget({ maxCalls: 3, maxTokens: 1000 });+ expect(b.total).toEqual({ calls: 3, tokens: 1000 });+ expect(b.remaining()).toEqual({ calls: 3, tokens: 1000 });++ b.charge(usage(400));+ expect(b.spent()).toEqual({ calls: 1, tokens: 400 });+ expect(b.remaining()).toEqual({ calls: 2, tokens: 600 });+ expect(b.exhausted()).toBe(false);++ b.charge(usage(700));+ expect(b.spent()).toEqual({ calls: 2, tokens: 1100 });+ expect(b.remaining()).toEqual({ calls: 1, tokens: 0 });+ expect(b.exhausted()).toBe(true); // tokens hit 0 even though a call remains+ });++ test("unset ceilings are unlimited", () => {+ const b = new Budget();+ expect(b.total).toEqual({ calls: Infinity, tokens: Infinity });+ b.charge(usage(1_000_000));+ expect(b.exhausted()).toBe(false);+ expect(b.remaining()).toEqual({ calls: Infinity, tokens: Infinity });+ });+});++// ── Run: budget admission ─────────────────────────────────────────────────++describe("Run budget admission", () => {+ test("exhausted budget stops admitting new agent() calls instead of erroring mid-fan-out", async () => {+ const dir = tmpJournalDir();+ try {+ const runner = new FakeRunner(() => ok("done", 10));+ const run = new Run({ dir, budget: { maxCalls: 2 }, runner });++ const r1 = await run.agent("task 1");+ const r2 = await run.agent("task 2");+ const r3 = await run.agent("task 3");++ expect(r1.ok).toBe(true);+ expect(r2.ok).toBe(true);+ expect(r3.ok).toBe(false);+ expect(r3.text).toMatch(/budget exhausted/i);+ expect(runner.calls.length).toBe(2); // the 3rd call never reached the runner+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});++// ── Run: journal write/replay + prefix resume ────────────────────────────++describe("Run journal + resume", () => {+ test("a warm, unchanged re-run replays every call from the journal (runner untouched)", async () => {+ const dir = tmpJournalDir();+ try {+ const runner1 = new FakeRunner((spec, n) => ok(`result-${n}:${spec.prompt}`, 5));+ const run1 = new Run({ dir: join(dir, "run1"), runner: runner1 });+ const results1 = [await run1.agent("task A"), await run1.agent("task B"), await run1.agent("task C")];+ expect(runner1.calls.length).toBe(3);+ expect(results1.every((r) => !r.cached)).toBe(true);++ const runner2 = new FakeRunner(() => {+ throw new Error("must not be called on a fully-cached replay");+ });+ const run2 = new Run({ dir: join(dir, "run2"), resumeFrom: run1.journalPath, runner: runner2 });+ const results2 = [await run2.agent("task A"), await run2.agent("task B"), await run2.agent("task C")];++ expect(results2.map((r) => r.text)).toEqual(results1.map((r) => r.text));+ expect(results2.every((r) => r.cached)).toBe(true);+ expect(runner2.calls.length).toBe(0);+ expect(run2.budget.spent()).toEqual({ calls: 0, tokens: 0 }); // replays never charge the budget+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("resume-prefix: a changed call reruns live, and everything after it does too", async () => {+ const dir = tmpJournalDir();+ try {+ const runner1 = new FakeRunner((spec, n) => ok(`v1-${n}:${spec.prompt}`, 5));+ const run1 = new Run({ dir: join(dir, "run1"), runner: runner1 });+ await run1.agent("task A");+ await run1.agent("task B");+ await run1.agent("task C");++ const runner2 = new FakeRunner((spec, n) => ok(`v2-${n}:${spec.prompt}`, 5));+ const run2 = new Run({ dir: join(dir, "run2"), resumeFrom: run1.journalPath, runner: runner2 });+ const rA = await run2.agent("task A"); // identical to run1 -> replayed+ const rB = await run2.agent("task B (changed)"); // diverges here -> live+ const rC = await run2.agent("task C"); // identical to run1, but AFTER the+ // divergence point -> still forced live (true prefix semantics, not+ // plain memoization: a later unchanged call doesn't get a free pass).++ expect(rA.cached).toBe(true);+ expect(rB.cached).toBe(false);+ expect(rC.cached).toBe(false);+ expect(runner2.calls.length).toBe(2); // B and C; A was never re-run+ expect(runner2.calls.map((s) => s.prompt)).toEqual(["task B (changed)", "task C"]);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("resumeFrom pointing at a nonexistent journal behaves like a fresh live run", async () => {+ const dir = tmpJournalDir();+ try {+ const runner = new FakeRunner((spec) => ok(spec.prompt));+ const run = new Run({ dir, resumeFrom: join(dir, "does-not-exist.jsonl"), runner });+ const r = await run.agent("hello");+ expect(r.cached).toBe(false);+ expect(runner.calls.length).toBe(1);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});++// ── agent(): opts passthrough (#276 P0-1/P0-3 surface) ───────────────────++describe("agent() opts passthrough", () => {+ test("isolation, isolationFallback, background, agent persona, and systemPrompt reach the spec", async () => {+ const runner = new FakeRunner((spec) => ok(spec.prompt));+ await agent("do the thing", {+ runner,+ agent: "researcher",+ isolation: "worktree",+ isolationFallback: true,+ background: true,+ systemPrompt: "custom persona text",+ });+ const spec = runner.calls[0];+ expect(spec.agent).toBe("researcher");+ expect(spec.isolation).toBe("worktree");+ expect(spec.isolationFallback).toBe(true);+ expect(spec.background).toBe(true);+ expect(spec.systemPrompt).toBe("custom persona text");+ });++ test("a bare agent() call (no {run}) is not journaled or budgeted", async () => {+ const runner = new FakeRunner((spec) => ok(spec.prompt));+ const r = await agent("one-off", { runner });+ expect(r.cached).toBe(false);+ expect(runner.calls.length).toBe(1);+ });+});++// ── Pure wire-format helpers (exercised without a live process) ─────────++describe("wire-format helpers", () => {+ test("subagentToolInput maps to the exact snake_case subagent tool schema", () => {+ const input = subagentToolInput({+ description: "fix it",+ prompt: "fix the bug",+ agent: "implementer",+ systemPrompt: "be terse",+ isolation: "worktree",+ isolationFallback: true,+ background: true,+ });+ expect(input).toEqual({+ description: "fix it",+ prompt: "fix the bug",+ agent: "implementer",+ system_prompt: "be terse",+ isolation: "worktree",+ isolation_fallback: true,+ run_in_background: true,+ });+ });++ test("subagentToolInput omits optional fields entirely when unset", () => {+ const input = subagentToolInput({ prompt: "just do it" });+ expect(input).toEqual({ description: "just do it", prompt: "just do it" });+ });++ test("parseBackgroundId parses spawnSubBackground's ack text", () => {+ expect(parseBackgroundId("[agent 7 started: fix the bug]\nIt runs in the background across turns...")).toBe(7);+ expect(parseBackgroundId("[agent 42 started: label]")).toBe(42);+ expect(parseBackgroundId("not an ack at all")).toBeNull();+ });+});diff --git a/sdk/ts/orchestrate.ts b/sdk/ts/orchestrate.tsnew file mode 100644index 00000000..08a9a137--- /dev/null+++ b/sdk/ts/orchestrate.ts@@ -0,0 +1,496 @@+// SDK orchestration layer (#276 P0-2) — hand-written, NOT auto-generated+// (contrast harness.ts/remote.ts's "Do not edit" header: this file is the+// place new SDK surface belongs). Realizes docs/hyperagents.md §3's framing+// ("the loop itself belongs in SDK code... not in the harness") for the+// third primitive that section names but never wired up: agent()/parallel()/+// pipeline() as first-class TS functions instead of one JSON blob the root+// LLM has to decide, on its own judgement, to emit as a `subagent`/+// `workflow` tool call.+//+// ── How agent() gets determinism out of an LLM loop ─────────────────────+// Each `agent()` call spawns its own short-lived `harness --json` process+// (idiomatic to this SDK's existing style — see runAgent in harness.ts) with+// its system prompt replaced by DISPATCH_SYSTEM_PROMPT: a rigid instruction+// to call exactly one named tool with an exact, SDK-supplied JSON input and+// nothing else. The SDK — not the model's judgement — fully determines the+// tool name and its input (including the isolation/run_in_background fields+// added by #276 P0-1/P0-3), so the only thing left to the model is executing+// one mechanical, fully-specified instruction; the result is read straight+// off that tool call's own `tool_result` event (never off the dispatcher's+// restated final answer), and background completions ride the same+// mechanism as a second scripted turn against `agent_output` on the same+// process (background jobs are process-local Zig state — see subagent.zig's+// g_agent_jobs — so spawn and poll must share one Harness). This is honest,+// LLM-instruction-following determinism, not hard protocol-level+// determinism; the orchestration *control flow* around it (concurrency,+// barriers, budget admission, journal replay) is what's actually+// deterministic, and that's the layer #276 P0-2 asks for.+//+// ── Journal format (JSONL, one record per LIVE agent() call) ────────────+// {"key":"a3","promptHash":"<sha256:16hex>","optsHash":"<sha256:16hex>",+// "ok":true,"text":"...","usage":{"durationMs":..,"toolCalls":..,+// "contextTokens":..,"cacheReadTokens":..},"ts":1700000000000}+//+// `key` is "a<N>": the Nth call made against a given Run's `agent()` /+// `Run.agent()`, N assigned by a synchronous counter at invocation time (not+// completion time), so two runs of the same deterministic script assign the+// same keys to the same logical calls regardless of real completion timing+// — this holds exactly for sequential (`await`ed one at a time) calls, and+// for calls made inside a single `parallel()`/`pipeline()` batch sized at or+// under the concurrency cap (the common case: all admitted synchronously, in+// array order, before any of them can complete — see `limitedMap`). Larger+// queued batches can admit item N+1 in completion order once the window is+// full, which is a documented, deliberate scope boundary: resume replay is+// exact for the tested/common shapes above and best-effort beyond them.+//+// Resume ("prefix replay"): `new Run({resumeFrom: <path to a prior+// journal.jsonl>})` loads it into a key -> record map. Each live call first+// checks that map by its own key: while nothing has diverged yet, a hit+// whose promptHash+optsHash both match replays the cached {ok, text, usage}+// with no runner call at all (never spawns a process, never re-charges the+// budget); the FIRST miss or hash mismatch flips a one-way `diverged` latch+// on the Run, and every call from that point on — even one that would, by+// coincidence, still match — runs live and gets appended fresh. That's the+// literal "prefix, then live from the first divergence" semantics: a warm+// re-run of an unchanged script touches the runner zero times; changing call+// k re-runs k and everything after it, byte-for-byte replaying 0..k-1.++import { createHash, randomBytes } from "node:crypto";+import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { Harness, promptFingerprint, type Event, type HarnessOptions } from "./harness.ts";++// ── Shared task shape ───────────────────────────────────────────────────++/** Fields the underlying `subagent` tool call accepts (schema.zig+ * `subagent_spec`) — src/fleet.zig's persona conventions apply to `agent`+ * (builtins: reviewer, researcher, implementer, skeptic, or a+ * `.harness/agents/<name>` override). */+export interface SubagentSpec {+ /** Short label for logs, 3-5 words. Defaults to a prompt prefix. */+ description?: string;+ /** Complete, self-contained task description for the child. */+ prompt: string;+ /** Named persona the child runs with. */+ agent?: string;+ /** Replace the child's system prompt outright (overrides `agent`). */+ systemPrompt?: string;+ /** #276 P0-1 passthrough: `"worktree"` gives this call its own scratch+ * git worktree instead of the shared working tree. */+ isolation?: "shared_cwd" | "worktree";+ /** If isolation:"worktree" fails to set up, run in the shared cwd instead+ * of failing the call. Default false, matching the tool's own default. */+ isolationFallback?: boolean;+ /** #276 P0-3 passthrough: run this subagent in the background on the+ * dispatching process, then poll it via `agent_output` on the same+ * process. Default false (synchronous). */+ background?: boolean;+}++export interface AgentOptions extends Omit<SubagentSpec, "prompt"> {+ /** Pins the dispatching harness process's model (and therefore the+ * child's, which inherits the parent's provider verbatim — see+ * subagent.zig's runSub: `.provider = ctx.provider`). */+ model?: string;+ /** Passthrough to the spawned Harness. `yolo` defaults to true: these are+ * non-interactive, fully scripted dispatches with nothing to confirm. */+ harness?: Pick<HarnessOptions, "binary" | "cwd" | "env" | "yolo">;+ /** Injectable transport. Defaults to a shared `HarnessRunner`; tests+ * substitute a fake so orchestration logic never needs a live binary. */+ runner?: AgentRunner;+ /** Attach this call to a `Run`'s budget/journal/concurrency instead of+ * running as a bare, unjournaled one-off. */+ run?: Run;+}++export interface AgentUsage {+ durationMs: number;+ toolCalls: number;+ contextTokens: number;+ cacheReadTokens: number;+}++export interface AgentResult {+ ok: boolean;+ text: string;+ usage: AgentUsage;+ /** true when replayed from a Run's journal instead of run live. */+ cached: boolean;+}++const zeroUsage: AgentUsage = { durationMs: 0, toolCalls: 0, contextTokens: 0, cacheReadTokens: 0 };++/** Injectable transport for `agent()` — the one seam that actually talks to+ * a `graff` process. Swap it in tests; production code never needs to. */+export interface AgentRunner {+ run(spec: SubagentSpec, opts: { model?: string; harness?: AgentOptions["harness"] }): Promise<AgentResult>;+}++// ── The real transport ──────────────────────────────────────────────────++const DISPATCH_SYSTEM_PROMPT =+ "You are a mechanical tool dispatcher, not a conversational assistant. " ++ 'On the turn you receive, call the exact tool named in it with the exact ' ++ "JSON input given — verbatim, unmodified — and nothing else: no commentary, " ++ "no other tool first, no attempt_completion. Exactly one tool call.";++function dispatchPrompt(toolName: string, input: Record<string, unknown>): string {+ return `Call the "${toolName}" tool exactly once with this exact JSON as its input (do not modify it): ${JSON.stringify(input)}`;+}++/** Builds the exact JSON `subagent` tool input for a spec (schema.zig+ * `subagent_spec` field names) — exported so the wire mapping is directly+ * unit-testable without a live process. */+export function subagentToolInput(spec: SubagentSpec): Record<string, unknown> {+ const input: Record<string, unknown> = {+ description: spec.description ?? spec.prompt.slice(0, 60),+ prompt: spec.prompt,+ };+ if (spec.agent) input.agent = spec.agent;+ if (spec.systemPrompt) input.system_prompt = spec.systemPrompt;+ if (spec.isolation) input.isolation = spec.isolation;+ if (spec.isolationFallback) input.isolation_fallback = true;+ if (spec.background) input.run_in_background = true;+ return input;+}++/** Parses the id out of spawnSubBackground's ack text (subagent.zig:531-535,+ * `"[agent {d} started: {s}]\n..."`). Exported so tests can pin the format+ * without needing a live process. */+export function parseBackgroundId(ackText: string): number | null {+ const m = /^\[agent (\d+) started:/.exec(ackText);+ return m ? Number(m[1]) : null;+}++function usageFromEvent(ev: Extract<Event, { type: "agent_usage" }>): AgentUsage {+ return {+ durationMs: ev.duration_ms,+ toolCalls: ev.tool_calls,+ contextTokens: ev.context_tokens,+ cacheReadTokens: ev.cache_read_tokens,+ };+}++/** Real `AgentRunner`: spawns a `graff --json` process per call and scripts+ * it into exactly one `subagent` tool call (see the file header). */+export class HarnessRunner implements AgentRunner {+ async run(spec: SubagentSpec, opts: { model?: string; harness?: AgentOptions["harness"] } = {}): Promise<AgentResult> {+ const h = new Harness({+ ...opts.harness,+ model: opts.model,+ yolo: opts.harness?.yolo ?? true,+ systemPrompt: DISPATCH_SYSTEM_PROMPT,+ });+ try {+ const first = await this.drive(h, dispatchPrompt("subagent", subagentToolInput(spec)), "subagent");+ if (!spec.background) {+ return first.result ?? { ok: false, text: "agent(): dispatcher never called the subagent tool", usage: first.usage, cached: false };+ }+ const id = first.result ? parseBackgroundId(first.result.text) : null;+ if (id === null) {+ return { ok: false, text: first.result?.text ?? "agent(): could not read a background agent id", usage: first.usage, cached: false };+ }+ const second = await this.drive(h, dispatchPrompt("agent_output", { id, wait_ms: 30000 }), "agent_output");+ return second.result ?? { ok: false, text: `agent(): agent_output never returned for id ${id}`, usage: second.usage, cached: false };+ } finally {+ h.close();+ }+ }++ /** Drive one scripted turn, stopping as soon as the target tool's+ * 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 result: AgentResult | null = null;+ for await (const ev of h.chat(prompt)) {+ if (ev.type === "agent_usage") usage = usageFromEvent(ev);+ if (ev.type === "tool_result" && ev.name === toolName) {+ result = { ok: !ev.is_error, text: ev.text, usage, cached: false };+ break;+ }+ if (ev.type === "error") throw new Error(ev.message);+ }+ return { result, usage };+ }+}++export const defaultRunner: AgentRunner = new HarnessRunner();++// ── Budget: budget.spent()/remaining()/total, fed by real AgentUsage ────++export interface BudgetTotals {+ calls: number;+ tokens: number;+}++export interface BudgetOptions {+ maxCalls?: number;+ maxTokens?: number;+}++/** Token-aware budget. Calls-based budgeting (`total.calls`) is the+ * existing RunBudget concept, counted SDK-side since the SDK itself+ * decides when each subagent call happens; token budgeting is additive,+ * fed by real `AgentUsage.contextTokens` off the `agent_usage` completion+ * event (#276 P0-2's one Zig-side change — see subagent.zig). */+export class Budget {+ readonly total: BudgetTotals;+ private _calls = 0;+ private _tokens = 0;++ constructor(opts: BudgetOptions = {}) {+ this.total = { calls: opts.maxCalls ?? Infinity, tokens: opts.maxTokens ?? Infinity };+ }++ spent(): BudgetTotals {+ return { calls: this._calls, tokens: this._tokens };+ }++ remaining(): BudgetTotals {+ return {+ calls: this.total.calls === Infinity ? Infinity : Math.max(0, this.total.calls - this._calls),+ tokens: this.total.tokens === Infinity ? Infinity : Math.max(0, this.total.tokens - this._tokens),+ };+ }++ /** True once either ceiling is used up — callers stop admitting new work+ * rather than erroring mid-fan-out. */+ exhausted(): boolean {+ const r = this.remaining();+ return r.calls <= 0 || r.tokens <= 0;+ }++ /** Record one live agent() call. Internal bookkeeping — agent()/Run.agent+ * call this; nothing else should. */+ charge(usage: AgentUsage): void {+ this._calls += 1;+ this._tokens += usage.contextTokens;+ }+}++// ── Concurrency ──────────────────────────────────────────────────────────++/** Matches run_budget.zig's `default_max_concurrency` / subagent.zig's+ * `max_concurrent_background_agents` (both 8) — the SDK-side fan-out cap is+ * sized the same as the core's, composing with it instead of racing past it+ * with a flood of independent processes. */+export const DEFAULT_CONCURRENCY = 8;++/** Concurrency-limited map. Admission is a fixed worker pool pulling from a+ * shared cursor: for `items.length <= limit`, every item's worker claims+ * its index synchronously up front (before any `fn` call can suspend), so+ * admission order == array order regardless of how long each `fn` actually+ * takes — the property both the no-barrier pipeline proof and journal-key+ * determinism above rely on. */+async function limitedMap<T, R>(items: readonly T[], limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]> {+ const results: R[] = new Array(items.length);+ let next = 0;+ const workerCount = Math.max(1, Math.min(limit, items.length || 1));+ const workers = Array.from({ length: workerCount }, async () => {+ while (next < items.length) {+ const i = next++;+ results[i] = await fn(items[i], i);+ }+ });+ await Promise.all(workers);+ return results;+}++// ── parallel(): explicit barrier, null-on-failure ───────────────────────++export interface ParallelOptions {+ concurrency?: number;+}++/** Fan out `thunks`, wait for all of them (the barrier — maps to+ * workflow.zig's phases mode), and never reject the batch: a thunk that+ * throws resolves as `null` at its index instead. Compose multiple+ * `parallel()` calls sequentially for a barrier BETWEEN phases. */+export async function parallel<T>(thunks: Array<() => Promise<T>>, opts: ParallelOptions = {}): Promise<Array<T | null>> {+ const limit = opts.concurrency ?? DEFAULT_CONCURRENCY;+ return limitedMap(thunks, limit, async (thunk) => {+ try {+ return await thunk();+ } catch {+ return null;+ }+ });+}++// ── pipeline(): per-item flow, no cross-stage barrier ───────────────────++/** One pipeline stage: receives the previous stage's result for THIS item+ * (undefined for the first stage), the original item, and its index. */+export type Stage<T> = (prev: unknown, item: T, index: number) => Promise<unknown>;++/** Map each item through `stages` independently — maps to workflow.zig's+ * pipeline mode (no barrier): item A can reach stage 3 while item B is+ * still on stage 1. A stage throwing fails only that item (resolves+ * `null`), mirroring parallel()'s null-on-failure convention. */+export async function pipeline<T>(items: T[], ...stages: Array<Stage<T>>): Promise<Array<unknown | null>> {+ return limitedMap(items, DEFAULT_CONCURRENCY, async (item, index) => {+ let prev: unknown = undefined;+ try {+ for (const stage of stages) prev = await stage(prev, item, index);+ return prev;+ } catch {+ return null;+ }+ });+}++// ── agent(): the one primitive that talks to a real process ─────────────++/** Run one subagent task. With no `opts.run` this is a bare, unjournaled,+ * unbudgeted one-off (still spawns via `opts.runner ?? defaultRunner`).+ * Pass `opts.run` to participate in a `Run`'s budget/journal/replay. */+export async function agent(prompt: string, opts: AgentOptions = {}): Promise<AgentResult> {+ const spec = toSpec(prompt, opts);+ if (opts.run) return opts.run.dispatch(spec, opts);+ const runner = opts.runner ?? defaultRunner;+ return runner.run(spec, { model: opts.model, harness: opts.harness });+}++function toSpec(prompt: string, opts: AgentOptions): SubagentSpec {+ return {+ prompt,+ description: opts.description,+ agent: opts.agent,+ systemPrompt: opts.systemPrompt,+ isolation: opts.isolation,+ isolationFallback: opts.isolationFallback,+ background: opts.background,+ };+}++function stableStringify(obj: Record<string, unknown>): string {+ const keys = Object.keys(obj)+ .filter((k) => obj[k] !== undefined)+ .sort();+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + JSON.stringify(obj[k])).join(",") + "}";+}++/** Everything about a call that changes what actually runs — excludes+ * transport plumbing (runner/harness/run) which isn't part of the task. */+function hashOpts(spec: SubagentSpec, model: string | undefined): string {+ const relevant = {+ agent: spec.agent,+ systemPrompt: spec.systemPrompt,+ isolation: spec.isolation,+ isolationFallback: spec.isolationFallback,+ background: spec.background,+ model,+ };+ return createHash("sha256").update(stableStringify(relevant)).digest("hex").slice(0, 16);+}++// ── Run: budget + JSONL journal + prefix resume ─────────────────────────++interface JournalRecord {+ key: string;+ promptHash: string;+ optsHash: string;+ ok: boolean;+ text: string;+ usage: AgentUsage;+ ts: number;+}++export interface RunOptions {+ /** Directory the journal is written under. Default: a fresh directory+ * under `.graff/journal/<run-id>/` off `process.cwd()`. */+ dir?: string;+ /** Path to a previous run's `journal.jsonl` to prefix-replay from. */+ resumeFrom?: string;+ budget?: BudgetOptions;+ concurrency?: number;+ runner?: AgentRunner;+}++/** An orchestration run: owns a `Budget`, a JSONL journal, and the+ * prefix-resume cursor described in the file header. Create one per+ * logical script invocation and pass it as `{run}` to every `agent()`+ * call that should be budgeted/journaled/resumable. */+export class Run {+ readonly id: string;+ readonly dir: string;+ readonly journalPath: string;+ readonly budget: Budget;+ readonly runner: AgentRunner;+ readonly concurrency: number;++ private nextSeq = 0;+ private diverged = false;+ private readonly oldByKey = new Map<string, JournalRecord>();++ constructor(opts: RunOptions = {}) {+ this.id = `${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`;+ this.dir = opts.dir ?? join(process.cwd(), ".graff", "journal", this.id);+ this.journalPath = join(this.dir, "journal.jsonl");+ this.budget = new Budget(opts.budget);+ this.runner = opts.runner ?? defaultRunner;+ this.concurrency = opts.concurrency ?? DEFAULT_CONCURRENCY;+ if (opts.resumeFrom) this.loadJournal(opts.resumeFrom);+ mkdirSync(this.dir, { recursive: true });+ }++ private loadJournal(path: string): void {+ if (!existsSync(path)) return;+ for (const line of readFileSync(path, "utf8").split("\n")) {+ if (!line.trim()) continue;+ try {+ const rec = JSON.parse(line) as JournalRecord;+ this.oldByKey.set(rec.key, rec);+ } catch {+ // A corrupt line loses that one cached call, not the whole resume.+ }+ }+ }++ private appendJournal(rec: JournalRecord): void {+ appendFileSync(this.journalPath, JSON.stringify(rec) + "\n");+ }++ /** Journaled, budgeted `agent()` call bound to this Run. */+ agent(prompt: string, opts: AgentOptions = {}): Promise<AgentResult> {+ return this.dispatch(toSpec(prompt, opts), opts);+ }++ /** Fan out on this Run's own concurrency default. Budget/journal+ * awareness comes from the thunks calling `run.agent()`/`agent(p,{run})`+ * themselves — see the file header for why parallel()/pipeline() stay+ * generic rather than reaching into opaque thunks. */+ runParallel<T>(thunks: Array<() => Promise<T>>): Promise<Array<T | null>> {+ return parallel(thunks, { concurrency: this.concurrency });+ }++ runPipeline<T>(items: T[], ...stages: Array<Stage<T>>): Promise<Array<unknown | null>> {+ return pipeline(items, ...stages);+ }++ /** @internal shared by the free `agent(prompt, {run})` form. */+ async dispatch(spec: SubagentSpec, opts: Pick<AgentOptions, "model" | "harness" | "runner">): Promise<AgentResult> {+ const key = "a" + this.nextSeq++;+ const promptHash = promptFingerprint(spec.prompt);+ const optsHash = hashOpts(spec, opts.model);++ if (!this.diverged) {+ const old = this.oldByKey.get(key);+ if (old && old.promptHash === promptHash && old.optsHash === optsHash) {+ return { ok: old.ok, text: old.text, usage: old.usage, cached: true };+ }+ this.diverged = true;+ }++ if (this.budget.exhausted()) {+ 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 });+ this.budget.charge(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.jsonindex 91a553e5..62ca189d 100644--- a/sdk/ts/package.json+++ b/sdk/ts/package.json@@ -16,6 +16,11 @@"import": "./remote.ts","default": "./remote.ts"},+ "./orchestrate": {+ "types": "./orchestrate.ts",+ "import": "./orchestrate.ts",+ "default": "./orchestrate.ts"+ },"./package.json": "./package.json"},"repository": {@@ -25,7 +30,16 @@},"homepage": "https://codegraff.com","keywords": ["codegraff", "graff", "agent", "llm", "harness", "sdk"],- "files": ["harness.ts", "remote.ts", "README.md"],+ "files": ["harness.ts", "remote.ts", "orchestrate.ts", "README.md"],"engines": { "node": ">=18" },- "license": "Apache-2.0"+ "license": "Apache-2.0",+ "scripts": {+ "typecheck": "tsc --noEmit -p tsconfig.json",+ "test": "bun test"+ },+ "devDependencies": {+ "@types/node": "^22.10.2",+ "bun-types": "^1.3.11",+ "typescript": "~5.9.3"+ }}diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.tsindex bfa84f59..cbe3a9f1 100644--- a/sdk/ts/remote.ts+++ b/sdk/ts/remote.ts@@ -7,10 +7,10 @@// `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.6";+export const HARNESS_VERSION = "0.8";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-build" | "k3" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | (string & {});-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow" | "learn_candidate";+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "codedb" | "todo_write" | "todo_read" | "eval" | "ask_user" | "attempt_completion" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate";export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";/** Events streamed by the bridge (same `--json` contract as the stdio SDK).@@ -29,6 +29,7 @@ export type Event =| { type: "ask_user"; call_id: string; question: string; input: Record<string, unknown> }| { type: "tool_result"; name: string; is_error: boolean; text: string }| { type: "tool_call_finished"; name: string; is_error: boolean; ms: number }+ | { type: "agent_usage"; id: string; ok: boolean; duration_ms: number; tool_calls: number; context_tokens: number; cache_read_tokens: number }| { type: "finalizing" }| { type: "turn"; text: string; context_tokens: number; cost_usd: number; complete?: boolean; metadata_complete?: boolean }| { type: "system_prompt"; ok: boolean; append: boolean; chars: number }@@ -250,4 +251,4 @@ export async function* runAgentRemote(opts: RunAgentRemoteOptions): AsyncGenerat}export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-build", "k3", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mlx-community/Qwen3.6-27B-OptiQ-4bit"];-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "learn_candidate"];+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "codedb", "todo_write", "todo_read", "eval", "ask_user", "attempt_completion", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate"];diff --git a/sdk/ts/tsconfig.json b/sdk/ts/tsconfig.jsonnew file mode 100644index 00000000..e4ca1960--- /dev/null+++ b/sdk/ts/tsconfig.json@@ -0,0 +1,18 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "lib": ["ES2022"],+ "module": "esnext",+ "moduleResolution": "bundler",+ "strict": true,+ "skipLibCheck": true,+ "verbatimModuleSyntax": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "noFallthroughCasesInSwitch": true,+ "noEmit": true,+ "allowImportingTsExtensions": true,+ "types": ["bun-types", "node"]+ },+ "include": ["*.ts"]+}diff --git a/src/schema.zig b/src/schema.zigindex f3834d9b..fd225fa2 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -39,6 +39,7 @@ const schema_protocol_json =\\ {"type": "ask_user", "call_id": "...", "question": "...", "input": {"question": "...", "options": ["..."]}},\\ {"type": "tool_result", "name": "tool", "is_error": false, "text": "..."},\\ {"type": "tool_call_finished", "name": "tool", "is_error": false, "ms": 0},+ \\ {"type": "agent_usage", "id": "sa-...", "ok": true, "duration_ms": 0, "tool_calls": 0, "context_tokens": 0, "cache_read_tokens": 0},\\ {"type": "finalizing"},\\ {"type": "turn", "text": "final assistant text", "context_tokens": 0, "cost_usd": 0.0, "complete": true, "metadata_complete": true},\\ {"type": "system_prompt", "ok": true, "append": false, "chars": 0},diff --git a/src/subagent.zig b/src/subagent.zigindex 41fa98aa..3ac86078 100644--- a/src/subagent.zig+++ b/src/subagent.zig@@ -188,6 +188,47 @@ pub const AgentUsage = struct {cache_read_tokens: u64 = 0,};+/// #276 P0-2: the wire shape of a subagent completion's usage event, emitted+/// on every runSub return (see the guiEmit call site below). A named struct+/// + pure constructor — not an inline anonymous literal — so the+/// id/ok/AgentUsage → wire-field mapping is unit-testable without needing+/// json_mode/g_out plumbing (same rationale as agentStatusText below).+const AgentUsageEvent = struct {+ type: []const u8 = "agent_usage",+ id: []const u8,+ ok: bool,+ duration_ms: u64,+ tool_calls: u32,+ context_tokens: u64,+ cache_read_tokens: u64,+};++fn agentUsageEvent(sub_id: []const u8, ok: bool, usage: AgentUsage) AgentUsageEvent {+ return .{+ .id = sub_id,+ .ok = ok,+ .duration_ms = usage.duration_ms,+ .tool_calls = usage.tool_calls,+ .context_tokens = usage.context_tokens,+ .cache_read_tokens = usage.cache_read_tokens,+ };+}++test "agentUsageEvent: maps AgentUsage fields onto the wire event without transposition (#276 P0-2)" {+ const ev = agentUsageEvent("sa-007-abcd", true, .{ .duration_ms = 4110, .tool_calls = 6, .context_tokens = 1820, .cache_read_tokens = 340 });+ try std.testing.expectEqualStrings("agent_usage", ev.type);+ try std.testing.expectEqualStrings("sa-007-abcd", ev.id);+ try std.testing.expect(ev.ok);+ try std.testing.expectEqual(@as(u64, 4110), ev.duration_ms);+ try std.testing.expectEqual(@as(u32, 6), ev.tool_calls);+ try std.testing.expectEqual(@as(u64, 1820), ev.context_tokens);+ try std.testing.expectEqual(@as(u64, 340), ev.cache_read_tokens);++ const failed = agentUsageEvent("sa-008-efgh", false, .{});+ try std.testing.expect(!failed.ok);+ try std.testing.expectEqual(@as(u64, 0), failed.duration_ms);+}+/// runSub's result: the tool-facing output plus the usage summary above./// Every direct caller (execSubagent, workflowTask, workflowRetryTask,/// judgeTask, workflow.zig's pipelineChain) only ever wanted `.output`@@ -307,6 +348,14 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const.context_tokens = agent.effectiveContextTokens(),.cache_read_tokens = agent.last_cache_read,};+ // #276 P0-2: every runSub completion — the synchronous execSubagent path+ // included, which historically discarded `usage` entirely (only a+ // background job's polled agent_output ever saw it) — now also emits a+ // structured completion event over the --json stream, so an SDK driving+ // the protocol programmatically can see real per-call token/duration+ // usage without needing run_in_background+agent_output for the common+ // synchronous case. No-ops outside --json mode (guiEmit).+ guiEmit(ctx.io, agentUsageEvent(sub_id, run_ok, usage));const fp = promptFingerprint(agent.systemPrompt());if (trace.g_traj) |tj| {tj.capturePrompt(fp, agent.systemPrompt());