| 1 | // End-to-end agent tasks: a real `wrangler dev` Worker, sandboxes in an |
| 2 | // `agent.mjs --sandbox-pool` process (containers don't run under wrangler dev), |
| 3 | // a fake model provider behind the model proxy, and the real git CLI. |
| 4 | // |
| 5 | // pnpm --filter @diffinery/app e2e |
| 6 | // |
| 7 | // Covers model keys (write-only, browser session only, opt-in), a task run end |
| 8 | // to end (sandbox as the agent, the model proxy adding the person's key, the |
| 9 | // push and the pull request as the agent), follow-ups, stopping, and the |
| 10 | // security rules: no token, agent or sandbox can start or steer a task, task |
| 11 | // sandboxes are closed to the sandbox API, and a run's model token stops |
| 12 | // working when the run ends. |
| 13 | import { spawn, execFileSync } from "node:child_process"; |
| 14 | import { mkdtempSync, writeFileSync, mkdirSync, rmSync, readdirSync, statSync, readFileSync, existsSync } from "node:fs"; |
| 15 | import { tmpdir } from "node:os"; |
| 16 | import { createHash, randomBytes } from "node:crypto"; |
| 17 | import { createRequire } from "node:module"; |
| 18 | import { join, dirname, resolve } from "node:path"; |
| 19 | import { fileURLToPath } from "node:url"; |
| 20 | import { createServer as netServer } from "node:net"; |
| 21 | import { createServer as httpServer } from "node:http"; |
| 22 | import { test, before, after } from "node:test"; |
| 23 | import assert from "node:assert/strict"; |
| 24 | |
| 25 | const APP = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); |
| 26 | const AGENT = resolve(APP, "../../containers/runner/dist/agent.mjs"); |
| 27 | const work = mkdtempSync(join(tmpdir(), "diffinery-tasks-e2e-")); |
| 28 | const poolRoot = join(work, "pool"); |
| 29 | // The terminal test speaks WebSocket with headers (Origin, cookies), which Node's built-in client can't set. |
| 30 | const { WebSocket: WS } = createRequire(resolve(APP, "../../containers/runner/package.json"))("ws"); |
| 31 | const RIVAL_SESSION = `rival-${randomBytes(12).toString("hex")}`; |
| 32 | const ANTHROPIC_KEY = `sk-ant-api03-${randomBytes(30).toString("hex")}`; |
| 33 | const OPENROUTER_KEY = `sk-or-v1-${randomBytes(32).toString("hex")}`; |
| 34 | let base; |
| 35 | let dev; |
| 36 | let pool; |
| 37 | let upstream; |
| 38 | let devLog = ""; |
| 39 | let poolLog = ""; |
| 40 | let token; |
| 41 | const modelRequests = []; |
| 42 | |
| 43 | const freePort = () => |
| 44 | new Promise((res) => { |
| 45 | const s = netServer(); |
| 46 | s.listen(0, "127.0.0.1", () => { |
| 47 | const { port } = s.address(); |
| 48 | s.close(() => res(port)); |
| 49 | }); |
| 50 | }); |
| 51 | |
| 52 | async function api(method, path, body, tok = token) { |
| 53 | const res = await fetch(`${base}/api/v3${path}`, { |
| 54 | method, |
| 55 | headers: { ...(tok === null ? {} : { authorization: `Bearer ${tok}` }), "content-type": "application/json" }, |
| 56 | body: body === undefined ? undefined : JSON.stringify(body), |
| 57 | }); |
| 58 | const text = await res.text(); |
| 59 | let json = null; |
| 60 | try { |
| 61 | json = text ? JSON.parse(text) : null; |
| 62 | } catch { |
| 63 | json = text; |
| 64 | } |
| 65 | return { status: res.status, json }; |
| 66 | } |
| 67 | async function ok(method, path, body, tok) { |
| 68 | const r = await api(method, path, body, tok); |
| 69 | assert.ok(r.status >= 200 && r.status < 300, `${method} ${path} -> ${r.status} ${JSON.stringify(r.json)}`); |
| 70 | return r.json; |
| 71 | } |
| 72 | /** As the signed-in person in a browser (the dev sign-in: no credentials). */ |
| 73 | const asPerson = (method, path, body) => api(method, path, body, null); |
| 74 | |
| 75 | const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); |
| 76 | async function until(what, fn, timeoutMs = 90_000) { |
| 77 | const end = Date.now() + timeoutMs; |
| 78 | let last; |
| 79 | while (Date.now() < end) { |
| 80 | last = await fn(); |
| 81 | if (last) return last; |
| 82 | await sleep(500); |
| 83 | } |
| 84 | assert.fail(`timed out waiting for ${what}\n--- wrangler log tail ---\n${devLog.slice(-4000)}\n--- pool log tail ---\n${poolLog.slice(-3000)}`); |
| 85 | } |
| 86 | |
| 87 | function git(cwd, args, tok = token) { |
| 88 | const auth = Buffer.from(`x-token:${tok}`).toString("base64"); |
| 89 | return execFileSync("git", ["-c", `http.extraHeader=Authorization: Basic ${auth}`, "-c", "protocol.version=2", ...args], { |
| 90 | cwd, |
| 91 | encoding: "utf8", |
| 92 | stdio: ["ignore", "pipe", "pipe"], |
| 93 | env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_AUTHOR_NAME: "E2E", GIT_AUTHOR_EMAIL: "e2e@example.com", GIT_COMMITTER_NAME: "E2E", GIT_COMMITTER_EMAIL: "e2e@example.com" }, |
| 94 | }); |
| 95 | } |
| 96 | |
| 97 | async function mcp(name, args, tok = token) { |
| 98 | const r = await fetch(`${base}/mcp`, { method: "POST", headers: { authorization: `Bearer ${tok}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }) }); |
| 99 | const { result } = await r.json(); |
| 100 | return result; |
| 101 | } |
| 102 | |
| 103 | /** The sandboxes the pool has started, newest first. */ |
| 104 | const poolSandboxes = () => |
| 105 | existsSync(poolRoot) |
| 106 | ? readdirSync(poolRoot) |
| 107 | .map((id) => ({ id, at: statSync(join(poolRoot, id)).mtimeMs })) |
| 108 | .sort((a, b) => b.at - a.at) |
| 109 | .map((x) => x.id) |
| 110 | : []; |
| 111 | |
| 112 | before(async () => { |
| 113 | if (!existsSync(AGENT)) execFileSync("pnpm", ["--filter", "@diffinery/runner", "build"], { cwd: APP, stdio: "pipe" }); |
| 114 | // A stand-in for the provider: records what reaches it and answers like the Messages API. |
| 115 | upstream = httpServer((req, res) => { |
| 116 | let body = ""; |
| 117 | req.on("data", (d) => (body += d)); |
| 118 | req.on("end", () => { |
| 119 | modelRequests.push({ method: req.method, url: req.url, headers: req.headers, body }); |
| 120 | res.writeHead(200, { "content-type": "application/json", "set-cookie": "upstream=1" }); |
| 121 | res.end(JSON.stringify({ type: "message", content: [{ type: "text", text: "fake model says hi" }] })); |
| 122 | }); |
| 123 | }); |
| 124 | await new Promise((r) => upstream.listen(0, "127.0.0.1", r)); |
| 125 | const upstreamUrl = `http://127.0.0.1:${upstream.address().port}`; |
| 126 | |
| 127 | const poolPort = await freePort(); |
| 128 | const poolSecret = randomBytes(16).toString("hex"); |
| 129 | pool = spawn("node", [AGENT, "--sandbox-pool", "--work-root", poolRoot], { env: { ...process.env, DIFFINERY_SANDBOX_POOL_SECRET: poolSecret, DIFFINERY_SANDBOX_PORT: String(poolPort) }, stdio: ["ignore", "pipe", "pipe"], detached: true }); |
| 130 | pool.stdout.on("data", (d) => (poolLog += d)); |
| 131 | pool.stderr.on("data", (d) => (poolLog += d)); |
| 132 | await until("sandbox pool", async () => poolLog.includes("listening"), 30_000); |
| 133 | |
| 134 | const port = await freePort(); |
| 135 | base = `http://127.0.0.1:${port}`; |
| 136 | const persist = join(work, "state"); |
| 137 | execFileSync("pnpm", ["exec", "wrangler", "d1", "migrations", "apply", "diffinery-dev", "--local", "-e", "dev", "--persist-to", persist], { cwd: APP, stdio: "pipe", env: { ...process.env, CI: "1" } }); |
| 138 | // A second person, signed in with a session: not the terminal's opener, whatever their role. |
| 139 | { |
| 140 | const at = new Date().toISOString(); |
| 141 | const later = new Date(Date.now() + 30 * 86400_000).toISOString(); |
| 142 | const hash = createHash("sha256").update(RIVAL_SESSION).digest("hex"); |
| 143 | execFileSync("pnpm", ["exec", "wrangler", "d1", "execute", "diffinery-dev", "--local", "-e", "dev", "--persist-to", persist, "--command", `INSERT INTO accounts (id, login, kind, name, status, created_at) VALUES ('u-rival', 'rival', 'user', 'Rival', 'active', '${at}'); INSERT INTO sessions (id, account_id, method, created_at, last_seen_at, expires_at) VALUES ('${hash}', 'u-rival', 'passkey', '${at}', '${at}', '${later}')`], { cwd: APP, stdio: "pipe", env: { ...process.env, CI: "1" } }); |
| 144 | } |
| 145 | const vars = { PUBLIC_URL: base, MASTER_KEY: randomBytes(32).toString("base64"), SANDBOX_POOL_URL: `http://127.0.0.1:${poolPort}`, SANDBOX_POOL_SECRET: poolSecret, MODEL_UPSTREAM_ANTHROPIC: upstreamUrl, MODEL_UPSTREAM_OPENAI: upstreamUrl, MODEL_UPSTREAM_OPENROUTER: upstreamUrl }; |
| 146 | dev = spawn("pnpm", ["exec", "wrangler", "dev", "-e", "dev", "--ip", "127.0.0.1", "--port", String(port), "--inspector-port", String(await freePort()), "--persist-to", persist, ...Object.entries(vars).flatMap(([k, v]) => ["--var", `${k}:${v}`]), "--show-interactive-dev-session=false"], { |
| 147 | cwd: APP, |
| 148 | env: { ...process.env, CI: "1", WRANGLER_SEND_METRICS: "false" }, |
| 149 | stdio: ["ignore", "pipe", "pipe"], |
| 150 | detached: true, |
| 151 | }); |
| 152 | dev.stdout.on("data", (d) => (devLog += d)); |
| 153 | dev.stderr.on("data", (d) => (devLog += d)); |
| 154 | await until( |
| 155 | "wrangler dev", |
| 156 | async () => { |
| 157 | try { |
| 158 | return (await fetch(`${base}/healthz`)).ok; |
| 159 | } catch { |
| 160 | return false; |
| 161 | } |
| 162 | }, |
| 163 | 120_000, |
| 164 | ); |
| 165 | const res = await fetch(`${base}/api/v3/diffinery/tokens`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "e2e", scopes: ["admin"] }) }); |
| 166 | assert.equal(res.status, 201, await res.clone().text()); |
| 167 | token = (await res.json()).token; |
| 168 | }); |
| 169 | |
| 170 | after(() => { |
| 171 | for (const p of [dev, pool]) { |
| 172 | if (p?.pid) { |
| 173 | try { |
| 174 | process.kill(-p.pid, "SIGTERM"); |
| 175 | } catch {} |
| 176 | } |
| 177 | } |
| 178 | upstream?.close(); |
| 179 | if (process.env.E2E_KEEP !== "1") rmSync(work, { recursive: true, force: true }); |
| 180 | }); |
| 181 | |
| 182 | test("model keys: write-only, browser session only, with an opt-in", async () => { |
| 183 | assert.deepEqual(await ok("GET", "/diffinery/model-keys"), []); |
| 184 | // No token can set one, however wide. |
| 185 | const viaToken = await api("PUT", "/diffinery/model-keys/anthropic", { key: ANTHROPIC_KEY, accept_terms: true }); |
| 186 | assert.equal(viaToken.status, 403, JSON.stringify(viaToken.json)); |
| 187 | assert.match(viaToken.json.message, /browser session/); |
| 188 | // The opt-in is required, and the key's shape is checked. |
| 189 | assert.equal((await asPerson("PUT", "/diffinery/model-keys/anthropic", { key: ANTHROPIC_KEY })).status, 422); |
| 190 | assert.equal((await asPerson("PUT", "/diffinery/model-keys/anthropic", { key: "sk-proj-not-anthropic-1234567890abcdef", accept_terms: true })).status, 422); |
| 191 | assert.equal((await asPerson("PUT", "/diffinery/model-keys/gemini", { key: ANTHROPIC_KEY, accept_terms: true })).status, 404); |
| 192 | const saved = await asPerson("PUT", "/diffinery/model-keys/anthropic", { key: ANTHROPIC_KEY, accept_terms: true }); |
| 193 | assert.equal(saved.status, 200, JSON.stringify(saved.json)); |
| 194 | assert.equal(saved.json.hint, ANTHROPIC_KEY.slice(-4)); |
| 195 | assert.ok(saved.json.opted_in_at); |
| 196 | // Never returned: not by the API, not on the page. |
| 197 | const listed = await ok("GET", "/diffinery/model-keys"); |
| 198 | assert.deepEqual(listed.map((k) => k.provider), ["anthropic"]); |
| 199 | assert.ok(!JSON.stringify(listed).includes(ANTHROPIC_KEY)); |
| 200 | const page = await (await fetch(`${base}/settings/model-access`)).text(); |
| 201 | assert.match(page, /Model access/); |
| 202 | assert.match(page, /Commercial Terms/); |
| 203 | assert.ok(page.includes(`…${ANTHROPIC_KEY.slice(-4)}`)); |
| 204 | assert.ok(!page.includes(ANTHROPIC_KEY)); |
| 205 | assert.equal((await api("DELETE", "/diffinery/model-keys/anthropic")).status, 403); |
| 206 | }); |
| 207 | |
| 208 | test("an agent task runs in a sandbox as the agent, through the model proxy, and opens a pull request", async () => { |
| 209 | const me = await ok("GET", "/user"); |
| 210 | const owner = me.login; |
| 211 | await ok("POST", "/user/repos", { name: "tasks-demo" }); |
| 212 | const src = join(work, "src"); |
| 213 | mkdirSync(src, { recursive: true }); |
| 214 | writeFileSync(join(src, "README.md"), "# tasks\n"); |
| 215 | git(src, ["init", "-q", "-b", "main"]); |
| 216 | git(src, ["add", "-A"]); |
| 217 | git(src, ["commit", "-q", "-m", "initial"]); |
| 218 | git(src, ["remote", "add", "origin", `${base}/${owner}/tasks-demo.git`]); |
| 219 | git(src, ["push", "-q", "origin", "main"]); |
| 220 | const R = `/repos/${owner}/tasks-demo/diffinery/tasks`; |
| 221 | const bot = (await asPerson("POST", "/diffinery/agents", { login: "task-bot", name: "Task Bot" })).json.token.token; |
| 222 | |
| 223 | const tokFile = join(work, "model-token"); |
| 224 | // The custom runtime: call the model through the proxy, show the key variable (masked), save the token for later, change a file. |
| 225 | const command = [ |
| 226 | `curl -sS -X POST "$ANTHROPIC_BASE_URL/v1/messages" -H "x-api-key: $ANTHROPIC_API_KEY" -H "content-type: application/json" -d '{"model":"m","messages":[]}'`, |
| 227 | "echo", |
| 228 | 'echo "key is $ANTHROPIC_API_KEY"', |
| 229 | `printf %s "$ANTHROPIC_API_KEY" > ${tokFile}`, |
| 230 | 'echo "goal: $DIFFINERY_TASK_PROMPT" | tail -1', |
| 231 | "echo hello > hello.txt", |
| 232 | ].join("; "); |
| 233 | const goal = "Add a hello file"; |
| 234 | |
| 235 | // Nobody but a person in a browser starts a task: not their token, not the agent's. |
| 236 | for (const tok of [token, bot]) { |
| 237 | const r = await api("POST", R, { goal, runtime: "custom", command, agent: "task-bot" }, tok); |
| 238 | assert.equal(r.status, 403, JSON.stringify(r.json)); |
| 239 | assert.match(r.json.message, /browser session/); |
| 240 | } |
| 241 | // Codex needs an OpenAI key the person doesn't have. |
| 242 | const codex = await asPerson("POST", R, { goal, runtime: "codex", agent: "task-bot" }); |
| 243 | assert.equal(codex.status, 422); |
| 244 | assert.match(codex.json.message, /OpenAI API key/); |
| 245 | assert.equal((await asPerson("POST", R, { goal, runtime: "custom", command, agent: owner })).status, 422, "a person isn't an agent"); |
| 246 | |
| 247 | const started = await asPerson("POST", R, { goal, runtime: "custom", command, agent: "task-bot" }); |
| 248 | assert.equal(started.status, 201, JSON.stringify(started.json)); |
| 249 | const n = started.json.number; |
| 250 | assert.equal(started.json.state, "running"); |
| 251 | assert.equal(started.json.branch, "agent/1-add-a-hello-file"); |
| 252 | assert.equal(started.json.agent.login, "task-bot"); |
| 253 | assert.equal(started.json.started_by.login, owner); |
| 254 | |
| 255 | const done = await until("the task to finish", async () => { |
| 256 | const t = await ok("GET", `${R}/${n}`); |
| 257 | return t.state !== "running" ? t : null; |
| 258 | }); |
| 259 | const lines = await ok("GET", `${R}/${n}/transcript`); |
| 260 | const text = lines.map((l) => `[${l.stream}] ${l.text}`).join("\n"); |
| 261 | assert.equal(done.state, "ready", text); |
| 262 | assert.ok(done.pull_request, text); |
| 263 | |
| 264 | // The provider got the person's key, never the run's token; the sandbox never saw the key. |
| 265 | assert.equal(modelRequests.length, 1, text); |
| 266 | assert.equal(modelRequests[0].headers["x-api-key"], ANTHROPIC_KEY); |
| 267 | assert.equal(modelRequests[0].url, "/v1/messages"); |
| 268 | assert.ok(!JSON.stringify(modelRequests[0].headers).includes("dmt_")); |
| 269 | assert.match(text, /fake model says hi/); |
| 270 | assert.match(text, /key is \*\*\*/, "the run's token is masked in the transcript"); |
| 271 | assert.match(text, /\[out\] Add a hello file/, "the prompt reaches the runtime"); |
| 272 | assert.ok(!text.includes(ANTHROPIC_KEY)); |
| 273 | const runToken = readFileSync(tokFile, "utf8"); |
| 274 | assert.match(runToken, /^dmt_/); |
| 275 | assert.ok(!text.includes(runToken)); |
| 276 | |
| 277 | // The run is over: its model token no longer works. |
| 278 | const late = await fetch(`${base}/-/model/anthropic/v1/messages`, { method: "POST", headers: { "x-api-key": runToken, "content-type": "application/json" }, body: "{}" }); |
| 279 | assert.equal(late.status, 401); |
| 280 | assert.equal(modelRequests.length, 1); |
| 281 | // Nor does the proxy take an account token, or anything outside /v1/. |
| 282 | assert.equal((await fetch(`${base}/-/model/anthropic/v1/messages`, { method: "POST", headers: { authorization: `Bearer ${token}` } })).status, 401); |
| 283 | assert.equal((await fetch(`${base}/-/model/anthropic/admin`, { headers: { "x-api-key": runToken } })).status, 403); |
| 284 | |
| 285 | // The pull request is the agent's, from the task's branch, with the work. |
| 286 | const pr = await ok("GET", `/repos/${owner}/tasks-demo/pulls/${done.pull_request.number}`); |
| 287 | assert.equal(pr.user.login, "task-bot"); |
| 288 | assert.equal(pr.head.ref, "agent/1-add-a-hello-file"); |
| 289 | assert.equal(pr.intent, goal); |
| 290 | const files = await ok("GET", `/repos/${owner}/tasks-demo/pulls/${pr.number}/files`); |
| 291 | assert.deepEqual(files.map((f) => f.filename), ["hello.txt"]); |
| 292 | const commit = await ok("GET", `/repos/${owner}/tasks-demo/commits/${pr.head.sha}`); |
| 293 | assert.equal(commit.commit.author.name, "task-bot"); |
| 294 | |
| 295 | // Read over MCP and on Today; steering is not on MCP. |
| 296 | const viaMcp = await mcp("agent_task", { owner, repo: "tasks-demo", number: n }); |
| 297 | assert.equal(viaMcp.isError, false, viaMcp.content[0].text); |
| 298 | assert.equal(viaMcp.structuredContent.state, "ready"); |
| 299 | assert.ok(viaMcp.structuredContent.transcript.length > 0); |
| 300 | const mine = await mcp("agent_tasks", {}); |
| 301 | assert.deepEqual(mine.structuredContent.result.map((t) => t.number), [n]); |
| 302 | const today = await ok("GET", "/diffinery/today"); |
| 303 | assert.equal(today.tasks[0].number, n); |
| 304 | assert.equal(today.tasks[0].state, "ready"); |
| 305 | |
| 306 | // Pages. |
| 307 | for (const path of ["tasks", `tasks/${n}`, "tasks/new"]) { |
| 308 | const res = await fetch(`${base}/${owner}/tasks-demo/${path}`); |
| 309 | assert.equal(res.status, 200, path); |
| 310 | } |
| 311 | const taskPage = await (await fetch(`${base}/${owner}/tasks-demo/tasks/${n}`)).text(); |
| 312 | assert.match(taskPage, /Add a hello file/); |
| 313 | assert.match(taskPage, /fake model says hi/); |
| 314 | |
| 315 | // Follow-ups and retries: the person, in a browser; never a token. |
| 316 | assert.equal((await api("POST", `${R}/${n}/messages`, { body: "again" })).status, 403); |
| 317 | assert.equal((await api("POST", `${R}/${n}/retry`, {})).status, 403); |
| 318 | assert.equal((await api("POST", `${R}/${n}/messages`, { body: "again" }, bot)).status, 403); |
| 319 | const followUp = await asPerson("POST", `${R}/${n}/messages`, { body: "Say hello again" }); |
| 320 | assert.equal(followUp.status, 201, JSON.stringify(followUp.json)); |
| 321 | const second = await until("the follow-up run", async () => { |
| 322 | const t = await ok("GET", `${R}/${n}`); |
| 323 | return t.state !== "running" ? t : null; |
| 324 | }); |
| 325 | assert.equal(second.state, "ready"); |
| 326 | assert.deepEqual(second.runs.map((r) => [r.kind, r.state]), [ |
| 327 | ["start", "done"], |
| 328 | ["message", "done"], |
| 329 | ]); |
| 330 | const text2 = (await ok("GET", `${R}/${n}/transcript?after=${lines.at(-1).seq}`)).map((l) => l.text).join("\n"); |
| 331 | assert.match(text2, /Say hello again/); |
| 332 | assert.match(text2, /No changes to push/); |
| 333 | assert.match(text2, /Starting a sandbox on agent\/1-add-a-hello-file/); |
| 334 | }); |
| 335 | |
| 336 | test("task sandboxes are closed to the sandbox API, and stopping ends the run's access", async () => { |
| 337 | const me = await ok("GET", "/user"); |
| 338 | const owner = me.login; |
| 339 | const R = `/repos/${owner}/tasks-demo/diffinery/tasks`; |
| 340 | const bot = (await asPerson("POST", "/diffinery/agents/task-bot/tokens", { name: "second" })).json.token; |
| 341 | const tokFile = join(work, "model-token-2"); |
| 342 | // An OpenRouter key too: its own shape, its own opt-in. |
| 343 | assert.equal((await asPerson("PUT", "/diffinery/model-keys/openrouter", { key: ANTHROPIC_KEY, accept_terms: true })).status, 422); |
| 344 | assert.equal((await asPerson("PUT", "/diffinery/model-keys/openrouter", { key: OPENROUTER_KEY })).status, 422); |
| 345 | assert.equal((await asPerson("PUT", "/diffinery/model-keys/openrouter", { key: OPENROUTER_KEY, accept_terms: true })).status, 200); |
| 346 | const before_ = new Set(poolSandboxes()); |
| 347 | const started = await asPerson("POST", R, { goal: "Wait a while", runtime: "custom", command: `printf %s "$ANTHROPIC_API_KEY" > ${tokFile}; sleep 120`, agent: "task-bot" }); |
| 348 | assert.equal(started.status, 201, JSON.stringify(started.json)); |
| 349 | const n = started.json.number; |
| 350 | const id = await until("the task's sandbox", async () => poolSandboxes().find((x) => !before_.has(x)) ?? null); |
| 351 | await until("the agent to start", async () => existsSync(tokFile)); |
| 352 | const runToken = readFileSync(tokFile, "utf8"); |
| 353 | |
| 354 | // While it runs, its token works through the proxy. |
| 355 | const live = await fetch(`${base}/-/model/anthropic/v1/messages`, { method: "POST", headers: { "x-api-key": runToken, "content-type": "application/json" }, body: "{}" }); |
| 356 | assert.equal(live.status, 200); |
| 357 | |
| 358 | // Only the model endpoints: not the rest of the person's provider account. |
| 359 | for (const [method, path] of [ |
| 360 | ["GET", "/v1/files"], |
| 361 | ["POST", "/v1/messages/batches"], |
| 362 | ["DELETE", "/v1/files/file_1"], |
| 363 | ]) { |
| 364 | const seen = modelRequests.length; |
| 365 | const r = await fetch(`${base}/-/model/anthropic${path}`, { method, headers: { "x-api-key": runToken, "content-type": "application/json" }, body: method === "POST" ? "{}" : undefined }); |
| 366 | assert.equal(r.status, 403, `${method} ${path}`); |
| 367 | assert.match((await r.json()).error.message, new RegExp(path.replace(/\//g, "\\/"))); |
| 368 | assert.equal(modelRequests.length, seen, `${method} ${path} must not reach the provider`); |
| 369 | } |
| 370 | |
| 371 | // OpenRouter: the run's token works there too (the custom runtime gets every provider the person has a key for), |
| 372 | // with the person's OpenRouter key and Diffinery's attribution added, and only its model endpoints. |
| 373 | const seenOr = modelRequests.length; |
| 374 | const orLive = await fetch(`${base}/-/model/openrouter/v1/chat/completions`, { method: "POST", headers: { authorization: `Bearer ${runToken}`, "content-type": "application/json", "x-title": "spoofed", "http-referer": "https://spoofed.example", referer: "https://spoofed.example", "x-openrouter-categories": "spoofed" }, body: '{"model":"anthropic/claude-sonnet-4.5","messages":[]}' }); |
| 375 | assert.equal(orLive.status, 200); |
| 376 | const orReq = modelRequests[seenOr]; |
| 377 | assert.equal(orReq.url, "/v1/chat/completions"); |
| 378 | assert.equal(orReq.headers.authorization, `Bearer ${OPENROUTER_KEY}`); |
| 379 | assert.equal(orReq.headers["x-api-key"], undefined); |
| 380 | assert.equal(orReq.headers["x-title"], "Diffinery"); |
| 381 | assert.equal(orReq.headers["http-referer"], base); |
| 382 | // Only Diffinery names itself to OpenRouter: the sandbox's attribution headers never reach it. |
| 383 | assert.equal(orReq.headers.referer, undefined); |
| 384 | assert.equal(orReq.headers["x-openrouter-categories"], undefined); |
| 385 | // Claude Code's way in: the Messages endpoint, with the token as a bearer token. |
| 386 | assert.equal((await fetch(`${base}/-/model/openrouter/v1/messages`, { method: "POST", headers: { authorization: `Bearer ${runToken}`, "content-type": "application/json" }, body: "{}" })).status, 200); |
| 387 | for (const [method, path] of [ |
| 388 | ["GET", "/v1/key"], |
| 389 | ["GET", "/v1/credits"], |
| 390 | ["GET", "/v1/keys"], |
| 391 | ["POST", "/v1/keys"], |
| 392 | ["GET", "/v1/generation"], |
| 393 | ["GET", "/v1/activity"], |
| 394 | ["GET", "/v1/models/user"], |
| 395 | ]) { |
| 396 | const seen = modelRequests.length; |
| 397 | const r = await fetch(`${base}/-/model/openrouter${path}`, { method, headers: { authorization: `Bearer ${runToken}`, "content-type": "application/json" }, body: method === "POST" ? "{}" : undefined }); |
| 398 | assert.equal(r.status, 403, `openrouter ${method} ${path}`); |
| 399 | assert.equal(modelRequests.length, seen, `openrouter ${method} ${path} must not reach the provider`); |
| 400 | } |
| 401 | |
| 402 | // No public sandbox call reaches it: the person (a repository admin here), their token, the agent. |
| 403 | for (const [who, tok] of [ |
| 404 | ["the person in a browser", null], |
| 405 | ["the person's admin token", token], |
| 406 | ["the agent's token", bot], |
| 407 | ]) { |
| 408 | for (const action of ["exec", "read", "write", "close"]) { |
| 409 | const r = await api("POST", `/repos/${owner}/tasks-demo/diffinery/sandboxes/${id}/${action}`, { cmd: "env", path: "README.md", content: "" }, tok); |
| 410 | assert.equal(r.status, 404, `${who} ${action}: ${JSON.stringify(r.json)}`); |
| 411 | } |
| 412 | } |
| 413 | for (const tool of ["sandbox_exec", "sandbox_read_file", "sandbox_write_file", "sandbox_close"]) { |
| 414 | const r = await mcp(tool, { owner, repo: "tasks-demo", sandbox_id: id, command: "env", path: "README.md", content: "" }, bot); |
| 415 | assert.equal(r.isError, true, tool); |
| 416 | assert.match(r.content[0].text, /sandbox not found/, tool); |
| 417 | } |
| 418 | |
| 419 | // A plain sandbox's own credential can't start or steer a task either. |
| 420 | const plain = await ok("POST", `/repos/${owner}/tasks-demo/diffinery/sandboxes`, {}, bot); |
| 421 | const cfgPath = join(poolRoot, plain.id, "repo", ".git", "config"); |
| 422 | const config = await until("the plain sandbox's git credential", async () => (existsSync(cfgPath) && /extraheader/i.test(readFileSync(cfgPath, "utf8")) ? readFileSync(cfgPath, "utf8") : null)); |
| 423 | const basic = /extraheader = Authorization: Basic (\S+)/i.exec(config); |
| 424 | assert.ok(basic, config); |
| 425 | const dst = Buffer.from(basic[1], "base64").toString().split(":").pop(); |
| 426 | assert.match(dst, /^dst_/); |
| 427 | assert.equal((await api("POST", R, { goal: "x", runtime: "custom", command: "true", agent: "task-bot" }, dst)).status, 403); |
| 428 | assert.equal((await api("POST", `${R}/${n}/messages`, { body: "x" }, dst)).status, 403); |
| 429 | await ok("POST", `/repos/${owner}/tasks-demo/diffinery/sandboxes/${plain.id}/close`, {}, bot); |
| 430 | |
| 431 | // One account keeps at most 5 sandboxes open in a repository; closing one makes room. |
| 432 | const open = []; |
| 433 | for (let i = 0; i < 5; i++) open.push((await ok("POST", `/repos/${owner}/tasks-demo/diffinery/sandboxes`, {}, bot)).id); |
| 434 | const sixth = await api("POST", `/repos/${owner}/tasks-demo/diffinery/sandboxes`, {}, bot); |
| 435 | assert.equal(sixth.status, 429); |
| 436 | assert.match(sixth.json.message, /5 open sandboxes in this repository/); |
| 437 | await ok("POST", `/repos/${owner}/tasks-demo/diffinery/sandboxes/${open.pop()}/close`, {}, bot); |
| 438 | open.push((await ok("POST", `/repos/${owner}/tasks-demo/diffinery/sandboxes`, {}, bot)).id); |
| 439 | for (const id of open) await ok("POST", `/repos/${owner}/tasks-demo/diffinery/sandboxes/${id}/close`, {}, bot); |
| 440 | |
| 441 | // The agent can stop its own task; the run's token stops working. |
| 442 | const stopped = await ok("POST", `${R}/${n}/stop`, {}, bot); |
| 443 | assert.equal(stopped.state, "stopped"); |
| 444 | const after_ = await fetch(`${base}/-/model/anthropic/v1/messages`, { method: "POST", headers: { "x-api-key": runToken, "content-type": "application/json" }, body: "{}" }); |
| 445 | assert.equal(after_.status, 401); |
| 446 | const t = await ok("GET", `${R}/${n}`); |
| 447 | assert.equal(t.runs[0].state, "stopped"); |
| 448 | assert.match((await ok("GET", `${R}/${n}/transcript`)).map((l) => l.text).join("\n"), /Stopped by task-bot/); |
| 449 | |
| 450 | // Claude Code and Codex can run through OpenRouter with a model of the person's choice; only combinations that work. |
| 451 | const form = await (await fetch(`${base}/${owner}/tasks-demo/tasks/new`)).text(); |
| 452 | assert.match(form, /claude-code\+openrouter","label":"Claude Code via OpenRouter/); |
| 453 | assert.match(form, /codex\+openrouter","label":"Codex via OpenRouter/); |
| 454 | for (const bad of [ |
| 455 | { runtime: "codex", provider: "anthropic" }, |
| 456 | { runtime: "custom", command: "true", provider: "openrouter" }, |
| 457 | { runtime: "claude-code", provider: "openrouter", model: "not a model" }, |
| 458 | { runtime: "claude-code", model: "anthropic/claude-sonnet-4.5" }, |
| 459 | ]) assert.equal((await asPerson("POST", R, { goal: "x", agent: "task-bot", ...bad })).status, 422, JSON.stringify(bad)); |
| 460 | const viaOr = await asPerson("POST", R, { goal: "Say hi", agent: "task-bot", runtime: "claude-code", provider: "openrouter", model: "anthropic/claude-sonnet-4.5" }); |
| 461 | assert.equal(viaOr.status, 201, JSON.stringify(viaOr.json)); |
| 462 | assert.equal(viaOr.json.runtime, "claude-code"); |
| 463 | assert.equal(viaOr.json.provider, "openrouter"); |
| 464 | assert.equal(viaOr.json.model, "anthropic/claude-sonnet-4.5"); |
| 465 | assert.equal((await ok("GET", `${R}/${viaOr.json.number}`)).provider, "openrouter"); |
| 466 | await ok("POST", `${R}/${viaOr.json.number}/stop`, {}, bot); |
| 467 | }); |
| 468 | |
| 469 | test("a repository is a project: settings, memory, conversation, and a queue of tasks", async () => { |
| 470 | const me = await ok("GET", "/user"); |
| 471 | const owner = me.login; |
| 472 | const P = `/repos/${owner}/tasks-demo/diffinery/project`; |
| 473 | const R = `/repos/${owner}/tasks-demo/diffinery/tasks`; |
| 474 | |
| 475 | // Settings: an admin in a browser; never a token. |
| 476 | assert.equal((await api("PUT", `${P}/settings`, { max_running: 1 })).status, 403); |
| 477 | for (const bad of [0, 11, 1.5, "x"]) assert.equal((await asPerson("PUT", `${P}/settings`, { max_running: bad })).status, 422, String(bad)); |
| 478 | assert.deepEqual((await asPerson("PUT", `${P}/settings`, { max_running: 1, instructions: "Always say PROJECT-RULE-7." })).json, { max_running: 1, instructions: "Always say PROJECT-RULE-7.", plan_first: "off" }); |
| 479 | |
| 480 | // Memory: every save is a version, and a restore is one more. |
| 481 | assert.equal((await api("PUT", `${P}/memory`, { body: "x" })).status, 403); |
| 482 | assert.equal((await asPerson("PUT", `${P}/memory`, { body: "MEMORY-NOTE-1: docs live in docs/." })).json.version, 1); |
| 483 | assert.equal((await asPerson("PUT", `${P}/memory`, { body: "MEMORY-NOTE-2: something wrong." })).json.version, 2); |
| 484 | assert.equal((await asPerson("PUT", `${P}/memory`, { restore: 99 })).status, 404); |
| 485 | const restored = await asPerson("PUT", `${P}/memory`, { restore: 1 }); |
| 486 | assert.equal(restored.json.version, 3); |
| 487 | assert.equal(restored.json.body, "MEMORY-NOTE-1: docs live in docs/."); |
| 488 | const memory = await ok("GET", `${P}/memory`); |
| 489 | assert.deepEqual(memory.versions.map((v) => v.version), [3, 2, 1]); |
| 490 | assert.equal(memory.updated_by.login, owner); |
| 491 | |
| 492 | // The conversation: people post in a browser. |
| 493 | assert.equal((await api("POST", `${P}/posts`, { body: "hi" })).status, 403); |
| 494 | assert.equal((await asPerson("POST", `${P}/posts`, { body: " " })).status, 422); |
| 495 | const idea = await asPerson("POST", `${P}/posts`, { body: "Idea: write a queued file" }); |
| 496 | assert.equal(idea.status, 201, JSON.stringify(idea.json)); |
| 497 | |
| 498 | // One at a time: the second task waits, then starts when the first ends. Both get the instructions and memory. |
| 499 | const command = (file, wait) => `printf '%s\\n' "$DIFFINERY_TASK_PROMPT" | grep -E 'PROJECT-RULE-7|MEMORY-NOTE|--- (instructions|memory) ---'; sleep ${wait}; echo ${file} > ${file}.txt`; |
| 500 | const a = await asPerson("POST", R, { goal: "Write the first file", runtime: "custom", command: command("first", 8), agent: "task-bot" }); |
| 501 | assert.equal(a.status, 201, JSON.stringify(a.json)); |
| 502 | const b = await asPerson("POST", R, { goal: "Write the queued file", runtime: "custom", command: command("queued", 0), agent: "task-bot" }); |
| 503 | assert.equal(b.status, 201, JSON.stringify(b.json)); |
| 504 | assert.equal(a.json.state, "running"); |
| 505 | assert.equal(b.json.state, "queued"); |
| 506 | const board = await ok("GET", P); |
| 507 | assert.deepEqual(board.board.working.map((t) => t.number), [a.json.number]); |
| 508 | assert.deepEqual(board.board.queued.map((t) => t.number), [b.json.number]); |
| 509 | assert.equal(board.settings.max_running, 1); |
| 510 | assert.equal(board.memory.version, 3); |
| 511 | const queuedLines = (await ok("GET", `${R}/${b.json.number}/transcript`)).map((l) => l.text).join("\n"); |
| 512 | assert.match(queuedLines, /Queued: 1 task is already running/); |
| 513 | const listed = (await ok("GET", `${R}?state=queued`)).map((t) => t.number); |
| 514 | assert.deepEqual(listed, [b.json.number]); |
| 515 | |
| 516 | const first = await until("the first task", async () => { |
| 517 | const t = await ok("GET", `${R}/${a.json.number}`); |
| 518 | return t.state !== "running" ? t : null; |
| 519 | }); |
| 520 | assert.equal(first.state, "ready"); |
| 521 | const second = await until("the queued task", async () => { |
| 522 | const t = await ok("GET", `${R}/${b.json.number}`); |
| 523 | return t.state === "ready" || t.state === "failed" ? t : null; |
| 524 | }); |
| 525 | const text = (await ok("GET", `${R}/${b.json.number}/transcript`)).map((l) => l.text).join("\n"); |
| 526 | assert.equal(second.state, "ready", text); |
| 527 | assert.ok(second.pull_request, text); |
| 528 | // The queued run started only after the first one ended. |
| 529 | assert.ok(Date.parse(second.runs[0].started_at) >= Date.parse(first.runs[0].ended_at), JSON.stringify([first.runs[0], second.runs[0]])); |
| 530 | for (const want of ["--- instructions ---", "PROJECT-RULE-7", "--- memory ---", "MEMORY-NOTE-1"]) assert.ok(text.includes(want), `${want}\n${text}`); |
| 531 | assert.ok(!text.includes("MEMORY-NOTE-2"), "the restored memory, not the replaced one"); |
| 532 | |
| 533 | // Tasks report to the conversation. |
| 534 | const posts = await ok("GET", `${P}/posts`); |
| 535 | const bodies = posts.map((p) => p.body); |
| 536 | assert.ok(bodies.includes("Idea: write a queued file")); |
| 537 | assert.ok(bodies.includes(`${owner} started task #${b.json.number}: Write the queued file`), bodies.join("\n")); |
| 538 | assert.ok(bodies.includes(`Task #${b.json.number} opened pull request #${second.pull_request.number}.`), bodies.join("\n")); |
| 539 | const later = await ok("GET", `${P}/posts?after=${idea.json.id}`); |
| 540 | assert.ok(later.every((p) => p.id > idea.json.id && p.kind === "event")); |
| 541 | |
| 542 | // Over MCP. |
| 543 | const viaMcp = await mcp("project", { owner, repo: "tasks-demo" }); |
| 544 | assert.equal(viaMcp.isError, false, viaMcp.content[0].text); |
| 545 | assert.equal(viaMcp.structuredContent.settings.max_running, 1); |
| 546 | const postsMcp = await mcp("project_posts", { owner, repo: "tasks-demo" }); |
| 547 | assert.equal(postsMcp.isError, false, postsMcp.content[0].text); |
| 548 | assert.ok(JSON.stringify(postsMcp.structuredContent).includes("Idea: write a queued file")); |
| 549 | |
| 550 | // Pages. |
| 551 | const projectPage = await (await fetch(`${base}/${owner}/tasks-demo/project`)).text(); |
| 552 | assert.match(projectPage, /Ready for review/); |
| 553 | assert.match(projectPage, /Write the queued file/); |
| 554 | assert.match(projectPage, /Idea: write a queued file/); |
| 555 | assert.match(projectPage, /MEMORY-NOTE-1/); |
| 556 | assert.match(projectPage, /href="\/[^"]+\/tasks-demo\/project" class="on"/); |
| 557 | const fromPost = await (await fetch(`${base}/${owner}/tasks-demo/tasks/new?post=${idea.json.id}`)).text(); |
| 558 | assert.match(fromPost, /Idea: write a queued file<\/textarea>/); |
| 559 | const memoryPage = await (await fetch(`${base}/${owner}/tasks-demo/project/memory?version=2`)).text(); |
| 560 | assert.match(memoryPage, /Restore this version/); |
| 561 | assert.match(memoryPage, /<tr class="del"><td class="ln">-<\/td><td class="code">MEMORY-NOTE-1/); |
| 562 | assert.match(memoryPage, /<tr class="add"><td class="ln">\+<\/td><td class="code">MEMORY-NOTE-2/); |
| 563 | const settingsPage = await (await fetch(`${base}/${owner}/tasks-demo/settings/project`)).text(); |
| 564 | assert.match(settingsPage, /name="max_running"[^>]*value="1"/); |
| 565 | assert.match(settingsPage, /Always say PROJECT-RULE-7\./); |
| 566 | |
| 567 | // The web forms work too, and raising the limit is what later tests need. |
| 568 | const form = async (path, fields) => { |
| 569 | const res = await fetch(`${base}/${owner}/tasks-demo/settings/project`); |
| 570 | const csrf = /name="_csrf" value="([^"]+)"/.exec(await res.text())?.[1]; |
| 571 | const cookie = /dfy_csrf=([^;]+)/.exec(res.headers.get("set-cookie") ?? "")?.[1]; |
| 572 | return fetch(`${base}/${owner}/tasks-demo/${path}`, { method: "POST", redirect: "manual", headers: { cookie: `dfy_csrf=${cookie}`, "sec-fetch-site": "same-origin" }, body: new URLSearchParams({ _csrf: csrf ?? "", ...fields }) }); |
| 573 | }; |
| 574 | assert.equal((await form("settings/project", { max_running: "0", instructions: "" })).status, 422); |
| 575 | assert.equal((await form("settings/project", { max_running: "3", instructions: "", plan_first: "sometimes" })).status, 422); |
| 576 | assert.equal((await form("settings/project", { max_running: "3", instructions: "", plan_first: "default" })).status, 303); |
| 577 | assert.deepEqual((await ok("GET", P)).settings, { max_running: 3, instructions: "", plan_first: "default" }); |
| 578 | assert.equal((await form("settings/project", { max_running: "3", instructions: "", plan_first: "off" })).status, 303); |
| 579 | assert.equal((await form("project/posts", { body: "Posted from the page" })).status, 303); |
| 580 | assert.ok((await ok("GET", `${P}/posts`)).some((p) => p.body === "Posted from the page")); |
| 581 | assert.equal((await form("project/memory/2/restore", {})).status, 303); |
| 582 | assert.equal((await ok("GET", `${P}/memory`)).body, "MEMORY-NOTE-2: something wrong."); |
| 583 | }); |
| 584 | |
| 585 | test("a coordinator turns posts into tasks, within its caps, and acts only through a validated block", async () => { |
| 586 | const me = await ok("GET", "/user"); |
| 587 | const owner = me.login; |
| 588 | const P = `/repos/${owner}/tasks-demo/diffinery/project`; |
| 589 | const R = `/repos/${owner}/tasks-demo/diffinery/tasks`; |
| 590 | // The coordinator and the tasks it starts run this script (the custom runtime), from the default branch. |
| 591 | const src = join(work, "src"); |
| 592 | writeFileSync( |
| 593 | join(src, "coord.sh"), |
| 594 | `p="$DIFFINERY_TASK_PROMPT" |
| 595 | case "$p" in |
| 596 | *"You are the project coordinator"*) |
| 597 | printf '%s\\n' "$p" | grep -E '^--- (post #|memory ---|instructions ---)' || true |
| 598 | post=$(printf '%s\\n' "$p" | sed -n '/^--- post #/,/^--- end of post ---/p') |
| 599 | case "$post" in |
| 600 | *BAD-BATCH*) printf '%s\\n' 'Checking.' '\`\`\`json' '{"reply": "Stopping it.", "stop": [999]}' '\`\`\`' ;; |
| 601 | *MSG-HAND*) printf '%s\\n' '\`\`\`json' '{"reply": "Nudging it.", "messages": [{"task": 1, "text": "Spend more."}]}' '\`\`\`' ;; |
| 602 | *MSG-OWN*) |
| 603 | n=$(printf '%s\\n' "$p" | sed -n 's/^- #\\([0-9]*\\) \\[[a-z]*\\] Small part .*started by you: you may message.*/\\1/p' | head -1) |
| 604 | printf '%s\\n' '\`\`\`json' "{\\"reply\\": \\"Following up on #$n.\\", \\"messages\\": [{\\"task\\": $n, \\"text\\": \\"Check it again.\\"}]}" '\`\`\`' ;; |
| 605 | *PLAN-THREE*) printf '%s\\n' '\`\`\`json' '{"reply": "Splitting it in three.", "tasks": [{"title": "Small part", "goal": "COORD-SMALL: write the small part."}, {"title": "Big part", "goal": "COORD-BIG: write the big part.", "after": [0]}, {"title": "Never part", "goal": "COORD-NEVER: never runs.", "after": [1]}], "memory": "MEMORY-BY-COORD: parts are split in three."}' '\`\`\`' ;; |
| 606 | *) printf '%s\\n' '\`\`\`json' '{"reply": "Noted, nothing to do."}' '\`\`\`' ;; |
| 607 | esac ;; |
| 608 | *COORD-SMALL*) |
| 609 | curl -s -o /dev/null -w "model %{http_code}\\n" -X POST "$ANTHROPIC_BASE_URL/v1/messages" -H "x-api-key: $ANTHROPIC_API_KEY" -H "content-type: application/json" -d '{"model":"m","max_tokens":5,"messages":[]}' |
| 610 | echo small > small.txt ;; |
| 611 | *COORD-BIG*) |
| 612 | curl -s -o /dev/null -w "model %{http_code}\\n" -X POST "$ANTHROPIC_BASE_URL/v1/messages" -H "x-api-key: $ANTHROPIC_API_KEY" -H "content-type: application/json" -d '{"model":"m","max_tokens":200000,"messages":[]}' |
| 613 | echo big > big.txt ;; |
| 614 | *) echo other > other.txt ;; |
| 615 | esac |
| 616 | `, |
| 617 | ); |
| 618 | git(src, ["pull", "-q", "--rebase", "origin", "main"]); |
| 619 | git(src, ["add", "coord.sh"]); |
| 620 | git(src, ["commit", "-q", "-m", "coordinator script"]); |
| 621 | git(src, ["push", "-q", "origin", "main"]); |
| 622 | |
| 623 | // Your coordinator: yours alone, set in a browser, with an opt-in to your key. |
| 624 | assert.deepEqual(await ok("GET", `${P}/coordinator`), { enabled: false }); |
| 625 | const settings = { agent: "task-bot", runtime: "custom", command: "sh coord.sh", tokens_per_task: 150000, accept: true }; |
| 626 | assert.equal((await api("PUT", `${P}/coordinator`, settings)).status, 403); |
| 627 | assert.equal((await asPerson("PUT", `${P}/coordinator`, { ...settings, accept: false })).status, 422); |
| 628 | assert.equal((await asPerson("PUT", `${P}/coordinator`, { ...settings, tokens_per_task: 5 })).status, 422); |
| 629 | assert.equal((await asPerson("PUT", `${P}/coordinator`, { ...settings, agent: owner })).status, 422); |
| 630 | const saved = await asPerson("PUT", `${P}/coordinator`, settings); |
| 631 | assert.equal(saved.status, 200, JSON.stringify(saved.json)); |
| 632 | assert.equal(saved.json.agent.login, "task-bot"); |
| 633 | assert.equal(saved.json.tokens_per_task, 150000); |
| 634 | assert.equal(saved.json.tokens_per_run, 1000000); |
| 635 | |
| 636 | const coordinatorRun = async (post) => |
| 637 | until(`the coordinator to handle post #${post}`, async () => { |
| 638 | const t = await ok("GET", `${R}/${post.task}`); |
| 639 | return t.runs.length >= post.run && t.runs[post.run - 1].state !== "boot" && !["queued", "boot", "install", "agent", "finish"].includes(t.runs[post.run - 1].state) ? t : null; |
| 640 | }); |
| 641 | |
| 642 | // A post goes to the poster's coordinator, which plans three tasks: the second after the first, the third after the second. |
| 643 | const plan = await asPerson("POST", `${P}/posts`, { body: "PLAN-THREE: split the work." }); |
| 644 | assert.equal(plan.status, 201, JSON.stringify(plan.json)); |
| 645 | assert.equal(plan.json.coordinator.status, "started"); |
| 646 | const coord = plan.json.coordinator.task; |
| 647 | const done = await coordinatorRun({ task: coord, run: 1 }); |
| 648 | const coordText = (await ok("GET", `${R}/${coord}/transcript`)).map((l) => l.text).join("\n"); |
| 649 | assert.equal(done.kind, "coordinator"); |
| 650 | assert.equal(done.runs[0].state, "done", coordText); |
| 651 | assert.match(coordText, new RegExp(`^--- post #${plan.json.id} by ${owner} ---$`, "m")); |
| 652 | assert.match(coordText, /^--- memory ---$/m, "the coordinator reads the memory"); |
| 653 | assert.match(coordText, /read-only sandbox/); |
| 654 | assert.match(coordText, /Applied: a reply, started #\d+, #\d+, #\d+, memory\./); |
| 655 | |
| 656 | const posts = await ok("GET", `${P}/posts?after=${plan.json.id - 1}`); |
| 657 | const reply = posts.find((p) => p.kind === "coordinator"); |
| 658 | assert.equal(reply.body, "Splitting it in three."); |
| 659 | assert.equal(reply.author.login, "task-bot"); |
| 660 | assert.equal(posts.find((p) => p.id === plan.json.id).handled_by.number, coord); |
| 661 | const started = posts.filter((p) => p.kind === "event" && p.body.startsWith(`${owner}'s coordinator started task`)); |
| 662 | assert.equal(started.length, 3, JSON.stringify(posts)); |
| 663 | const [a, b, c] = started.map((p) => p.task.number); |
| 664 | const memEvent = posts.find((p) => p.memory_version); |
| 665 | assert.match(memEvent.body, /changed the project memory to version \d+: 1 line added, 1 removed\./); |
| 666 | assert.equal((await ok("GET", `${P}/memory`)).body, "MEMORY-BY-COORD: parts are split in three."); |
| 667 | |
| 668 | const ta = await ok("GET", `${R}/${a}`); |
| 669 | assert.deepEqual(ta.started_via, { type: "coordinator", post: plan.json.id }); |
| 670 | assert.equal(ta.token_budget, 150000); |
| 671 | assert.equal(ta.title, "Small part"); |
| 672 | assert.equal(ta.goal, "COORD-SMALL: write the small part."); |
| 673 | assert.deepEqual((await ok("GET", `${R}/${b}`)).waits_for, [a]); |
| 674 | |
| 675 | // The first runs; the second starts only when the first is ready, and its budget stops it; the third never starts. |
| 676 | const ra = await until("the first part", async () => { |
| 677 | const t = await ok("GET", `${R}/${a}`); |
| 678 | return ["ready", "failed", "stopped"].includes(t.state) ? t : null; |
| 679 | }); |
| 680 | const textA = (await ok("GET", `${R}/${a}/transcript`)).map((l) => l.text).join("\n"); |
| 681 | assert.equal(ra.state, "ready", textA); |
| 682 | assert.match(textA, /model 200/); |
| 683 | assert.match(textA, new RegExp(`${owner}'s coordinator started the task`)); |
| 684 | const rb = await until("the second part", async () => { |
| 685 | const t = await ok("GET", `${R}/${b}`); |
| 686 | return ["ready", "failed", "stopped"].includes(t.state) ? t : null; |
| 687 | }); |
| 688 | const textB = (await ok("GET", `${R}/${b}/transcript`)).map((l) => l.text).join("\n"); |
| 689 | assert.equal(rb.state, "failed", textB); |
| 690 | assert.match(textB, /Queued: it starts when task #\d+ is ready\./); |
| 691 | assert.match(rb.error, /The run's next model request could take it past its budget of 150k tokens/); |
| 692 | assert.ok(Date.parse(rb.runs[0].started_at) >= Date.parse(ra.runs[0].ended_at)); |
| 693 | const rc = await until("the third part to be stopped", async () => { |
| 694 | const t = await ok("GET", `${R}/${c}`); |
| 695 | return t.state === "stopped" ? t : null; |
| 696 | }); |
| 697 | assert.equal(rc.error, `Task #${b}, which this task waits for, failed.`); |
| 698 | assert.deepEqual(rc.runs.map((r) => r.state), ["stopped"]); |
| 699 | |
| 700 | // An invalid batch is rejected whole: nothing is applied. |
| 701 | const memoryBefore = (await ok("GET", `${P}/memory`)).version; |
| 702 | const bad = await asPerson("POST", `${P}/posts`, { body: "BAD-BATCH: stop someone else's task." }); |
| 703 | assert.equal(bad.json.coordinator.task, coord); |
| 704 | const badRun = await coordinatorRun({ task: coord, run: 2 }); |
| 705 | assert.equal(badRun.runs[1].state, "failed"); |
| 706 | assert.match(badRun.runs[1].error, /Its actions were rejected: stop\[0\] must be one of the tasks you may stop\. Nothing was applied\./); |
| 707 | const afterBad = await ok("GET", `${P}/posts?after=${bad.json.id}`); |
| 708 | assert.ok(!afterBad.some((p) => p.kind === "coordinator"), "no reply was posted"); |
| 709 | assert.ok(afterBad.some((p) => p.body === `${owner}'s coordinator didn't finish handling post #${bad.json.id}: ${badRun.runs[1].error}`), JSON.stringify(afterBad)); |
| 710 | assert.equal((await ok("GET", `${P}/memory`)).version, memoryBefore); |
| 711 | // It may only message tasks it started (their runs have a budget), never the person's own hand-started ones. |
| 712 | const hand = await asPerson("POST", `${P}/posts`, { body: "MSG-HAND: nudge task one." }); |
| 713 | const handRun = await coordinatorRun({ task: coord, run: 3 }); |
| 714 | assert.match(handRun.runs[2].error, /messages\[0\]\.task must be one of the tasks you may message/); |
| 715 | assert.equal((await ok("GET", `${R}/1`)).runs.length, 2, "task #1 got no new run"); |
| 716 | void hand; |
| 717 | const own = await asPerson("POST", `${P}/posts`, { body: "MSG-OWN: follow up on your own task." }); |
| 718 | const ownRun = await coordinatorRun({ task: coord, run: 4 }); |
| 719 | assert.equal(ownRun.runs[3].state, "done", JSON.stringify(ownRun.runs[3])); |
| 720 | void own; |
| 721 | const followed = await until("the follow-up on the first part", async () => { |
| 722 | const t = await ok("GET", `${R}/${a}`); |
| 723 | return t.runs.length === 2 && !["queued", "boot", "install", "agent", "finish"].includes(t.runs[1].state) ? t : null; |
| 724 | }); |
| 725 | assert.equal(followed.runs[1].kind, "message"); |
| 726 | assert.match(followed.runs[1].message, new RegExp(`^\\(From ${owner}'s coordinator, handling post #\\d+\\.\\)\\nCheck it again\\.$`)); |
| 727 | |
| 728 | // A post can skip the coordinator, and be handed to it later, once. |
| 729 | const quiet = await asPerson("POST", `${P}/posts`, { body: "Just a note.", coordinator: false }); |
| 730 | assert.equal(quiet.json.coordinator, null); |
| 731 | assert.equal((await api("POST", `${P}/posts/${quiet.json.id}/handle`)).status, 403); |
| 732 | const handled = await asPerson("POST", `${P}/posts/${quiet.json.id}/handle`); |
| 733 | assert.equal(handled.status, 202, JSON.stringify(handled.json)); |
| 734 | assert.equal((await asPerson("POST", `${P}/posts/${quiet.json.id}/handle`)).status, 409); |
| 735 | const third = await coordinatorRun({ task: coord, run: 5 }); |
| 736 | assert.equal(third.runs[4].state, "done"); |
| 737 | assert.ok((await ok("GET", `${P}/posts?after=${quiet.json.id}`)).some((p) => p.kind === "coordinator" && p.body === "Noted, nothing to do.")); |
| 738 | // A coordinator takes no messages and isn't retried. |
| 739 | assert.equal((await asPerson("POST", `${R}/${coord}/messages`, { body: "hi" })).status, 409); |
| 740 | |
| 741 | // The board leaves the coordinator out; the pages show its work. |
| 742 | const board = await ok("GET", P); |
| 743 | assert.ok(!Object.values(board.board).flat().some((t) => t.number === coord)); |
| 744 | const page = await (await fetch(`${base}/${owner}/tasks-demo/project`)).text(); |
| 745 | assert.match(page, /Splitting it in three\./); |
| 746 | assert.match(page, /badge purple">Coordinator/); |
| 747 | assert.match(page, /The change to the memory/); |
| 748 | assert.match(page, /<tr class="add"><td class="ln">\+<\/td><td class="code">MEMORY-BY-COORD/); |
| 749 | assert.match(page, /Hand this to my coordinator/); |
| 750 | assert.equal((await fetch(`${base}/${owner}/tasks-demo/project/coordinator`)).status, 200); |
| 751 | const taskPage = await (await fetch(`${base}/${owner}/tasks-demo/tasks/${a}`)).text(); |
| 752 | assert.match(taskPage, /coordinator started this task while handling/); |
| 753 | |
| 754 | // Turning it off: posts stay posts. |
| 755 | assert.equal((await asPerson("DELETE", `${P}/coordinator`)).status, 204); |
| 756 | assert.deepEqual(await ok("GET", `${P}/coordinator`), { enabled: false }); |
| 757 | const after = await asPerson("POST", `${P}/posts`, { body: "PLAN-THREE again" }); |
| 758 | assert.equal(after.json.coordinator, null); |
| 759 | assert.equal((await asPerson("POST", `${P}/posts/${after.json.id}/handle`)).status, 422); |
| 760 | }); |
| 761 | |
| 762 | test("plan first: a read-only plan run, then approve, change or split the plan", async () => { |
| 763 | const me = await ok("GET", "/user"); |
| 764 | const owner = me.login; |
| 765 | const P = `/repos/${owner}/tasks-demo/diffinery/project`; |
| 766 | const R = `/repos/${owner}/tasks-demo/diffinery/tasks`; |
| 767 | const src = join(work, "src"); |
| 768 | writeFileSync( |
| 769 | join(src, "plan.sh"), |
| 770 | `p="$DIFFINERY_TASK_PROMPT" |
| 771 | case "$p" in |
| 772 | *"You are the project coordinator"*) |
| 773 | post=$(printf '%s\\n' "$p" | sed -n '/^--- post #/,/^--- end of post ---/p') |
| 774 | case "$post" in |
| 775 | *"Split the plan of task #"*"PLAN-V1-STEP"*) printf '%s\\n' '\`\`\`json' '{"reply": "Split it.", "tasks": [{"title": "Plan part one", "goal": "PLAN-PART-ONE: build step one."}]}' '\`\`\`' ;; |
| 776 | *) printf '%s\\n' '\`\`\`json' '{"reply": "Noted."}' '\`\`\`' ;; |
| 777 | esac ;; |
| 778 | *"You are planning task"*) |
| 779 | echo planned > should-not-land.txt |
| 780 | git add -A && git commit -qm "plan run commit" && git push -q origin HEAD:refs/heads/plan-run-push 2>/dev/null && echo "PUSHED" >&2 |
| 781 | case "$p" in |
| 782 | *"Your previous plan:"*"Use the KV store"*) printf '%s\\n' '## Plan' '1. PLAN-V2-STEP: write planned.txt, with the KV store.' ;; |
| 783 | *) printf '%s\\n' '## Plan' '1. PLAN-V1-STEP: write planned.txt.' ;; |
| 784 | esac ;; |
| 785 | *"approved. Follow it:"*) |
| 786 | printf '%s\\n' "$p" | sed -n '/^--- plan ---$/,/^--- end of plan ---$/p' |
| 787 | echo built > planned.txt ;; |
| 788 | *PLAN-PART-ONE*) echo part > part.txt ;; |
| 789 | *) echo other > other.txt ;; |
| 790 | esac |
| 791 | `, |
| 792 | ); |
| 793 | git(src, ["pull", "-q", "--rebase", "origin", "main"]); |
| 794 | git(src, ["add", "plan.sh"]); |
| 795 | git(src, ["commit", "-q", "-m", "plan script"]); |
| 796 | git(src, ["push", "-q", "origin", "main"]); |
| 797 | const settled = (n, what, fn = () => true) => |
| 798 | until(what, async () => { |
| 799 | const t = await ok("GET", `${R}/${n}`); |
| 800 | const last = t.runs.at(-1); |
| 801 | return last && !["queued", "boot", "install", "agent", "finish"].includes(last.state) && fn(t) ? t : null; |
| 802 | }); |
| 803 | const transcript = async (n) => (await ok("GET", `${R}/${n}/transcript`)).map((l) => l.text).join("\n"); |
| 804 | |
| 805 | // A plan-first task's first run plans in a read-only sandbox: nothing it changes is pushed. |
| 806 | assert.equal((await asPerson("POST", R, { goal: "x", runtime: "custom", command: "sh plan.sh", agent: "task-bot", plan_first: "yes" })).status, 422); |
| 807 | const started = await asPerson("POST", R, { goal: "PLANNED-GOAL: write planned.txt", runtime: "custom", command: "sh plan.sh", agent: "task-bot", plan_first: true }); |
| 808 | assert.equal(started.status, 201, JSON.stringify(started.json)); |
| 809 | const n = started.json.number; |
| 810 | assert.equal(started.json.plan_first, true); |
| 811 | assert.equal(started.json.plan_state, "planning"); |
| 812 | const planned = await settled(n, "the plan"); |
| 813 | const text1 = await transcript(n); |
| 814 | assert.equal(planned.runs[0].kind, "plan"); |
| 815 | assert.equal(planned.runs[0].state, "done", text1); |
| 816 | assert.equal(planned.state, "ready"); |
| 817 | assert.equal(planned.plan_state, "waiting"); |
| 818 | assert.match(planned.plan, /^## Plan\n1\. PLAN-V1-STEP: write planned\.txt\.$/); |
| 819 | assert.equal(planned.pull_request, null); |
| 820 | assert.match(text1, /Starting a read-only sandbox to plan on main as task-bot\./); |
| 821 | assert.match(text1, /It plans first\./); |
| 822 | assert.ok(!text1.includes("PUSHED"), "the plan run's push was refused"); |
| 823 | assert.equal(git(src, ["ls-remote", "origin", "refs/heads/plan-run-push", `refs/heads/${planned.branch}`]).trim(), "", "nothing was pushed"); |
| 824 | const board = await ok("GET", P); |
| 825 | assert.ok(board.board.waiting.some((t) => t.number === n), "a plan waiting for approval waits on you"); |
| 826 | assert.ok((await ok("GET", `${P}/posts`)).some((p) => p.body === `Task #${n}'s plan needs approval.`)); |
| 827 | const page = await (await fetch(`${base}/${owner}/tasks-demo/tasks/${n}`)).text(); |
| 828 | assert.match(page, /PLAN-V1-STEP/); |
| 829 | assert.match(page, /Approve plan/); |
| 830 | |
| 831 | // Asking for changes plans again, with the plan it replaces. |
| 832 | assert.equal((await asPerson("POST", `${R}/${n}/messages`, { body: "Use the KV store" })).status, 201); |
| 833 | const replanned = await settled(n, "the second plan", (t) => t.runs.length === 2); |
| 834 | assert.equal(replanned.runs[1].kind, "plan"); |
| 835 | assert.equal(replanned.plan_state, "waiting"); |
| 836 | assert.match(replanned.plan, /PLAN-V2-STEP/); |
| 837 | assert.match(await transcript(n), /Planning again with the changes asked for\./); |
| 838 | |
| 839 | // Approving starts the build run, which carries the approved plan; only a person in a browser may approve. |
| 840 | assert.equal((await api("POST", `${R}/${n}/plan/approve`)).status, 403); |
| 841 | const approved = await asPerson("POST", `${R}/${n}/plan/approve`); |
| 842 | assert.equal(approved.status, 202, JSON.stringify(approved.json)); |
| 843 | assert.equal(approved.json.plan_state, "approved"); |
| 844 | assert.equal((await asPerson("POST", `${R}/${n}/plan/approve`)).status, 409); |
| 845 | const built = await settled(n, "the build", (t) => t.runs.length === 3); |
| 846 | const text3 = await transcript(n); |
| 847 | assert.equal(built.runs[2].kind, "build"); |
| 848 | assert.equal(built.runs[2].state, "done", text3); |
| 849 | assert.match(text3, /The plan is approved: building it\./); |
| 850 | assert.match(text3, /^--- plan ---\n## Plan\n1\. PLAN-V2-STEP: write planned\.txt, with the KV store\.\n--- end of plan ---$/m); |
| 851 | assert.ok(built.pull_request, "the build opened a pull request"); |
| 852 | assert.ok((await ok("GET", `${P}/posts`)).some((p) => p.body === `${owner} approved the plan of task #${n}.`)); |
| 853 | // A follow-up after approval is an ordinary run, still with the plan. |
| 854 | assert.equal((await asPerson("POST", `${R}/${n}/messages`, { body: "One more thing" })).status, 201); |
| 855 | const after = await settled(n, "the follow-up", (t) => t.runs.length === 4); |
| 856 | assert.equal(after.runs[3].kind, "message"); |
| 857 | |
| 858 | // A project can require plans: every task plans first, ticked or not, including ones coordinators start. |
| 859 | assert.equal((await asPerson("PUT", `${P}/settings`, { plan_first: "always" })).status, 422); |
| 860 | assert.equal((await asPerson("PUT", `${P}/settings`, { plan_first: "required" })).json.plan_first, "required"); |
| 861 | const forced = await asPerson("POST", R, { goal: "SPLIT-GOAL: a goal to split", runtime: "custom", command: "sh plan.sh", agent: "task-bot", plan_first: false }); |
| 862 | assert.equal(forced.status, 201, JSON.stringify(forced.json)); |
| 863 | const m = forced.json.number; |
| 864 | assert.equal(forced.json.plan_first, true); |
| 865 | await settled(m, "the plan to split", (t) => t.plan_state === "waiting"); |
| 866 | |
| 867 | // Splitting hands the plan to the person's coordinator; the tasks it starts link back, and the task is done with. |
| 868 | assert.equal((await asPerson("POST", `${R}/${m}/plan/split`)).status, 422, "no coordinator yet"); |
| 869 | const coord = await asPerson("PUT", `${P}/coordinator`, { agent: "task-bot", runtime: "custom", command: "sh plan.sh", accept: true }); |
| 870 | assert.equal(coord.status, 200, JSON.stringify(coord.json)); |
| 871 | assert.equal((await asPerson("POST", `${R}/${n}/plan/split`)).status, 409, "an approved plan can't be split"); |
| 872 | assert.equal((await api("POST", `${R}/${m}/plan/split`)).status, 403); |
| 873 | const split = await asPerson("POST", `${R}/${m}/plan/split`); |
| 874 | assert.equal(split.status, 202, JSON.stringify(split.json)); |
| 875 | assert.equal((await asPerson("POST", `${R}/${m}/plan/split`)).status, 409); |
| 876 | const splitPost = (await ok("GET", `${P}/posts?after=${split.json.post - 1}`)).find((p) => p.id === split.json.post); |
| 877 | assert.match(splitPost.body, new RegExp(`^Split the plan of task #${m} \\(SPLIT-GOAL: a goal to split\\) into tasks\\.`)); |
| 878 | assert.equal(splitPost.author.login, owner); |
| 879 | const child = await until("the coordinator to split the plan", async () => { |
| 880 | const posts = await ok("GET", `${P}/posts?after=${split.json.post}`); |
| 881 | const ev = posts.find((p) => p.kind === "event" && p.body.startsWith(`${owner}'s coordinator started task`)); |
| 882 | return ev ? ev.task.number : null; |
| 883 | }); |
| 884 | const c = await ok("GET", `${R}/${child}`); |
| 885 | assert.equal(c.parent_task, m); |
| 886 | assert.equal(c.title, "Plan part one"); |
| 887 | assert.equal(c.plan_first, true, "a coordinator's task plans first when the project requires it"); |
| 888 | const parent = await ok("GET", `${R}/${m}`); |
| 889 | assert.equal(parent.plan_state, "split"); |
| 890 | assert.ok((await ok("GET", P)).board.idle.some((t) => t.number === m)); |
| 891 | const childPage = await (await fetch(`${base}/${owner}/tasks-demo/tasks/${child}`)).text(); |
| 892 | assert.match(childPage, new RegExp(`Split from the plan of <a href="[^"]*/tasks/${m}">task #${m}</a>`)); |
| 893 | await settled(child, "the child's plan", (t) => t.plan_state === "waiting"); |
| 894 | |
| 895 | assert.equal((await asPerson("PUT", `${P}/settings`, { plan_first: "off" })).json.plan_first, "off"); |
| 896 | assert.equal((await asPerson("DELETE", `${P}/coordinator`)).status, 204); |
| 897 | }); |
| 898 | |
| 899 | test("best of N: attempts run side by side on their own branches, then one is picked", async () => { |
| 900 | const me = await ok("GET", "/user"); |
| 901 | const owner = me.login; |
| 902 | const P = `/repos/${owner}/tasks-demo/diffinery/project`; |
| 903 | const R = `/repos/${owner}/tasks-demo/diffinery/tasks`; |
| 904 | const src = join(work, "src"); |
| 905 | // Attempts get the same prompt; each claims a slot (the e2e pool's sandboxes share /tmp) and does different work. |
| 906 | writeFileSync( |
| 907 | join(src, "best.sh"), |
| 908 | `p="$DIFFINERY_TASK_PROMPT" |
| 909 | case "$p" in |
| 910 | *"New instructions from"*) echo follow > follow.txt; echo FOLLOWED-UP; exit 0 ;; |
| 911 | esac |
| 912 | tag=$(printf '%s\\n' "$p" | grep -o 'BEST-[a-z0-9]*' | head -1) |
| 913 | slot=0 |
| 914 | for i in 1 2 3 4; do if mkdir "/tmp/$tag-$i" 2>/dev/null; then slot=$i; break; fi; done |
| 915 | case $slot in |
| 916 | 1) echo one > one.txt; echo SUMMARY-ONE-FILE ;; |
| 917 | 2) echo a > a.txt; echo b > b.txt; echo c > c.txt; echo SUMMARY-THREE-FILES ;; |
| 918 | *) echo SLOT-FAIL; exit 3 ;; |
| 919 | esac |
| 920 | `, |
| 921 | ); |
| 922 | git(src, ["pull", "-q", "--rebase", "origin", "main"]); |
| 923 | git(src, ["add", "best.sh"]); |
| 924 | git(src, ["commit", "-q", "-m", "best of N script"]); |
| 925 | git(src, ["push", "-q", "origin", "main"]); |
| 926 | const tag = `BEST-${randomBytes(6).toString("hex")}`; |
| 927 | const start = { goal: `${tag}: try it three ways`, runtime: "custom", command: "sh best.sh", agent: "task-bot" }; |
| 928 | |
| 929 | for (const bad of [0, 5, 1.5, "x"]) assert.equal((await asPerson("POST", R, { ...start, attempts: bad })).status, 422, String(bad)); |
| 930 | const started = await asPerson("POST", R, { ...start, attempts: 3 }); |
| 931 | assert.equal(started.status, 201, JSON.stringify(started.json)); |
| 932 | const n = started.json.number; |
| 933 | assert.equal(started.json.attempts, 3); |
| 934 | assert.equal(started.json.pick_state, "running"); |
| 935 | assert.deepEqual(started.json.runs.map((r) => r.attempt), [1, 2, 3]); |
| 936 | |
| 937 | // They run together, each on its own branch; the task waits on you when the last one ends. |
| 938 | const done = await until("the attempts", async () => { |
| 939 | const t = await ok("GET", `${R}/${n}`); |
| 940 | return !["running", "queued"].includes(t.state) ? t : null; |
| 941 | }); |
| 942 | const text = (await ok("GET", `${R}/${n}/transcript`)).map((l) => l.text).join("\n"); |
| 943 | assert.equal(done.state, "ready", text); |
| 944 | assert.equal(done.pick_state, "waiting"); |
| 945 | assert.equal(done.pull_request, null, "no pull request until a pick"); |
| 946 | assert.match(text, new RegExp(`Attempt 2 of 3, on ${done.branch}-a2\\.`)); |
| 947 | assert.ok((await ok("GET", P)).board.waiting.some((t) => t.number === n), "attempts to pick from wait on you"); |
| 948 | assert.ok((await ok("GET", `${P}/posts`)).some((p) => p.body === `Task #${n}'s 3 attempts are done: 2 of them pushed work to compare. Pick one.`)); |
| 949 | |
| 950 | const attempts = await ok("GET", `${R}/${n}/attempts`); |
| 951 | assert.equal(attempts.length, 3); |
| 952 | assert.deepEqual(attempts.map((a) => a.branch), [done.branch, `${done.branch}-a2`, `${done.branch}-a3`]); |
| 953 | const failed = attempts.find((a) => a.state === "failed"); |
| 954 | const one = attempts.find((a) => a.changes.files === 1); |
| 955 | const three = attempts.find((a) => a.changes.files === 3); |
| 956 | assert.ok(failed && one && three, JSON.stringify(attempts)); |
| 957 | assert.equal(failed.head_sha, null); |
| 958 | assert.match(one.summary, /SUMMARY-ONE-FILE/); |
| 959 | assert.match(three.summary, /SUMMARY-THREE-FILES/); |
| 960 | assert.deepEqual(three.changes, { files: 3, additions: 3, deletions: 0 }); |
| 961 | for (const a of [one, three]) assert.equal(git(src, ["ls-remote", "origin", `refs/heads/${a.branch}`]).trim().split(/\s/)[0], a.head_sha); |
| 962 | const page = await (await fetch(`${base}/${owner}/tasks-demo/tasks/${n}`)).text(); |
| 963 | assert.match(page, /<h2>Attempts<\/h2>/); |
| 964 | assert.match(page, new RegExp(`/tasks/${n}/attempts/${three.attempt}/pick`)); |
| 965 | |
| 966 | // Follow-ups wait for a pick; only the person who started it may pick, and only an attempt with work. |
| 967 | assert.equal((await asPerson("POST", `${R}/${n}/messages`, { body: "go on" })).status, 409); |
| 968 | assert.equal((await api("POST", `${R}/${n}/attempts/${three.attempt}/pick`)).status, 403); |
| 969 | assert.equal((await asPerson("POST", `${R}/${n}/attempts/${failed.attempt}/pick`)).status, 422); |
| 970 | assert.equal((await asPerson("POST", `${R}/${n}/attempts/9/pick`)).status, 404); |
| 971 | const picked = await asPerson("POST", `${R}/${n}/attempts/${three.attempt}/pick`); |
| 972 | assert.equal(picked.status, 202, JSON.stringify(picked.json)); |
| 973 | assert.equal(picked.json.picked_attempt, three.attempt); |
| 974 | assert.equal(picked.json.pick_state, "picked"); |
| 975 | assert.equal(picked.json.branch, three.branch); |
| 976 | assert.ok(picked.json.pull_request, "picking opens the pull request"); |
| 977 | const pr = await ok("GET", `/repos/${owner}/tasks-demo/pulls/${picked.json.pull_request.number}`); |
| 978 | assert.equal(pr.head.ref, three.branch); |
| 979 | assert.equal(git(src, ["ls-remote", "origin", `refs/heads/${one.branch}`]).trim(), "", "the other attempt's branch is deleted"); |
| 980 | assert.equal((await asPerson("POST", `${R}/${n}/attempts/${one.attempt}/pick`)).status, 409); |
| 981 | assert.ok((await ok("GET", `${P}/posts`)).some((p) => p.body === `${owner} picked attempt ${three.attempt} of task #${n}.`)); |
| 982 | |
| 983 | // Later runs build on the picked attempt. |
| 984 | assert.equal((await asPerson("POST", `${R}/${n}/messages`, { body: "Add a follow file" })).status, 201); |
| 985 | const next = await until("the follow-up", async () => { |
| 986 | const t = await ok("GET", `${R}/${n}`); |
| 987 | return t.runs.length === 4 && !["queued", "boot", "install", "agent", "finish"].includes(t.runs[3].state) ? t : null; |
| 988 | }); |
| 989 | assert.equal(next.runs[3].state, "done"); |
| 990 | assert.equal(next.runs[3].attempt, undefined); |
| 991 | assert.match((await ok("GET", `${R}/${n}/transcript`)).map((l) => l.text).join("\n"), new RegExp(`Starting a sandbox on ${three.branch} as task-bot\\.`)); |
| 992 | const files = (await ok("GET", `/repos/${owner}/tasks-demo/pulls/${pr.number}/files`)).map((f) => f.filename).sort(); |
| 993 | assert.deepEqual(files, ["a.txt", "b.txt", "c.txt", "follow.txt"]); |
| 994 | for (let i = 1; i <= 4; i++) rmSync(`/tmp/${tag}-${i}`, { recursive: true, force: true }); |
| 995 | }); |
| 996 | |
| 997 | test("verify and land: failing checks start a fix run, and an approved pull request lands", async () => { |
| 998 | const me = await ok("GET", "/user"); |
| 999 | const owner = me.login; |
| 1000 | const P = `/repos/${owner}/tasks-demo/diffinery/project`; |
| 1001 | const R = `/repos/${owner}/tasks-demo/diffinery/tasks`; |
| 1002 | const REPO = `/repos/${owner}/tasks-demo`; |
| 1003 | const src = join(work, "src"); |
| 1004 | writeFileSync( |
| 1005 | join(src, "verify.sh"), |
| 1006 | `p="$DIFFINERY_TASK_PROMPT" |
| 1007 | case "$p" in |
| 1008 | *"Checks failed on pull request"*) printf '%s\\n' "$p" | grep -E '^(--- |New instructions from|CI-SAYS)' ; echo fixed > fixed.txt ;; |
| 1009 | *) echo work > verify.txt ;; |
| 1010 | esac |
| 1011 | `, |
| 1012 | ); |
| 1013 | git(src, ["pull", "-q", "--rebase", "origin", "main"]); |
| 1014 | git(src, ["add", "verify.sh"]); |
| 1015 | git(src, ["commit", "-q", "-m", "verify script"]); |
| 1016 | git(src, ["push", "-q", "origin", "main"]); |
| 1017 | // An unprotected branch to land on: agents may have pull requests merged into it automatically, once a person approves. |
| 1018 | git(src, ["push", "-q", "origin", "main:refs/heads/release"]); |
| 1019 | |
| 1020 | const start = { goal: "VERIFY-GOAL: write verify.txt", runtime: "custom", command: "sh verify.sh", agent: "task-bot", base: "release" }; |
| 1021 | assert.equal((await asPerson("POST", R, { ...start, land: "yes" })).status, 422); |
| 1022 | const started = await asPerson("POST", R, { ...start, land: true }); |
| 1023 | assert.equal(started.status, 201, JSON.stringify(started.json)); |
| 1024 | const n = started.json.number; |
| 1025 | assert.equal(started.json.fix_checks, true, "on by default"); |
| 1026 | assert.equal(started.json.land, true); |
| 1027 | const ready = await until("the task's pull request", async () => { |
| 1028 | const t = await ok("GET", `${R}/${n}`); |
| 1029 | return t.state !== "running" && t.state !== "queued" ? t : null; |
| 1030 | }); |
| 1031 | assert.equal(ready.state, "ready", JSON.stringify(ready)); |
| 1032 | const pr = ready.pull_request.number; |
| 1033 | assert.match((await ok("GET", `${R}/${n}/transcript`)).map((l) => l.text).join("\n"), new RegExp(`Auto-merge is on for #${pr}: it lands once a person approves it and its checks pass\\.`)); |
| 1034 | const pull = await ok("GET", `${REPO}/pulls/${pr}`); |
| 1035 | assert.ok(pull.auto_merge, "auto-merge is on"); |
| 1036 | assert.equal(pull.merged, false, "not without a person's approval"); |
| 1037 | |
| 1038 | // A failing check on the head starts one fix run, with what the check said. |
| 1039 | const head = pull.head.sha; |
| 1040 | await ok("POST", `${REPO}/statuses/${head}`, { state: "failure", context: "ci/verify", description: "CI-SAYS: verify.txt is wrong" }); |
| 1041 | const fixing = await until("the fix run", async () => { |
| 1042 | const t = await ok("GET", `${R}/${n}`); |
| 1043 | return t.runs.length === 2 && !["queued", "boot", "install", "agent", "finish"].includes(t.runs[1].state) ? t : null; |
| 1044 | }); |
| 1045 | const text = (await ok("GET", `${R}/${n}/transcript`)).map((l) => l.text).join("\n"); |
| 1046 | assert.equal(fixing.runs[1].kind, "fix"); |
| 1047 | assert.equal(fixing.runs[1].state, "done", text); |
| 1048 | assert.equal(fixing.check_fixes, 1); |
| 1049 | assert.match(text, /^--- ci\/verify: failure ---$/m); |
| 1050 | assert.match(text, /^CI-SAYS: verify\.txt is wrong$/m); |
| 1051 | assert.match(text, /^New instructions from Diffinery \(the pull request's checks failed\):$/m); |
| 1052 | assert.ok((await ok("GET", `${P}/posts`)).some((p) => p.body === `Task #${n}'s pull request #${pr} failed checks; starting fix run 1 of 3.`)); |
| 1053 | const fixedHead = (await ok("GET", `${REPO}/pulls/${pr}`)).head.sha; |
| 1054 | assert.notEqual(fixedHead, head); |
| 1055 | // The same failure reported again on the old head starts nothing more. |
| 1056 | await ok("POST", `${REPO}/statuses/${head}`, { state: "failure", context: "ci/other" }); |
| 1057 | await ok("POST", `${REPO}/statuses/${fixedHead}`, { state: "success", context: "ci/verify" }); |
| 1058 | await sleep(3000); |
| 1059 | assert.equal((await ok("GET", `${R}/${n}`)).runs.length, 2); |
| 1060 | |
| 1061 | // Options: only the person who started it, in a browser. |
| 1062 | assert.equal((await api("PATCH", `${R}/${n}`, { land: false })).status, 403); |
| 1063 | assert.equal((await asPerson("PATCH", `${R}/${n}`, { fix_checks: "no" })).status, 422); |
| 1064 | const off = await asPerson("PATCH", `${R}/${n}`, { fix_checks: false }); |
| 1065 | assert.equal(off.status, 200, JSON.stringify(off.json)); |
| 1066 | assert.equal(off.json.fix_checks, false); |
| 1067 | assert.match(await (await fetch(`${base}/${owner}/tasks-demo/tasks/${n}`)).text(), /<h2>Verify and land<\/h2>/); |
| 1068 | |
| 1069 | // A person approves: it lands by itself. |
| 1070 | const review = await api("POST", `${REPO}/pulls/${pr}/reviews`, { event: "APPROVE", commit_id: fixedHead }); |
| 1071 | assert.ok(review.status < 300, JSON.stringify(review.json)); |
| 1072 | const merged = await until("the pull request to land", async () => { |
| 1073 | const p = await ok("GET", `${REPO}/pulls/${pr}`); |
| 1074 | return p.merged ? p : null; |
| 1075 | }); |
| 1076 | assert.equal(merged.merged, true); |
| 1077 | assert.ok((await ok("GET", P)).board.done.some((t) => t.number === n), "a landed task is done"); |
| 1078 | }); |
| 1079 | |
| 1080 | test("losing access to the agent stops the task", async () => { |
| 1081 | const me = await ok("GET", "/user"); |
| 1082 | const owner = me.login; |
| 1083 | const R = `/repos/${owner}/tasks-demo/diffinery/tasks`; |
| 1084 | const tokFile = join(work, "model-token-3"); |
| 1085 | const started = await asPerson("POST", R, { goal: "Lose access", runtime: "custom", command: `printf %s "$ANTHROPIC_API_KEY" > ${tokFile}; sleep 120`, agent: "task-bot" }); |
| 1086 | assert.equal(started.status, 201, JSON.stringify(started.json)); |
| 1087 | const n = started.json.number; |
| 1088 | await until("the agent to start", async () => existsSync(tokFile)); |
| 1089 | const runToken = readFileSync(tokFile, "utf8"); |
| 1090 | // Disabling the agent ends its access, and with it the task's. |
| 1091 | assert.equal((await api("DELETE", "/diffinery/agents/task-bot")).status, 204); |
| 1092 | const refused = await fetch(`${base}/-/model/anthropic/v1/messages`, { method: "POST", headers: { "x-api-key": runToken, "content-type": "application/json" }, body: "{}" }); |
| 1093 | assert.equal(refused.status, 403); |
| 1094 | const t = await until("the task to stop", async () => { |
| 1095 | const x = await ok("GET", `${R}/${n}`); |
| 1096 | return x.state !== "running" ? x : null; |
| 1097 | }); |
| 1098 | assert.equal(t.state, "stopped"); |
| 1099 | assert.equal((await fetch(`${base}/-/model/anthropic/v1/messages`, { method: "POST", headers: { "x-api-key": runToken }, body: "{}" })).status, 401); |
| 1100 | }); |
| 1101 | |
| 1102 | /** Opens a terminal's WebSocket; resolves with the HTTP status when the upgrade is refused. */ |
| 1103 | function termSocket(url, headers) { |
| 1104 | return new Promise((resolve) => { |
| 1105 | const ws = new WS(url, { headers }); |
| 1106 | let out = ""; |
| 1107 | ws.on("message", (d, binary) => { |
| 1108 | if (binary) out += String(d); |
| 1109 | }); |
| 1110 | let closedWith = null; |
| 1111 | const closed = new Promise((r) => ws.on("close", (code, reason) => r((closedWith = { code, reason: String(reason) })))); |
| 1112 | ws.once("unexpected-response", (_req, res) => resolve({ status: res.statusCode })); |
| 1113 | ws.once("error", (e) => resolve({ status: 0, error: e.message })); |
| 1114 | ws.once("open", () => |
| 1115 | resolve({ |
| 1116 | status: 101, |
| 1117 | ws, |
| 1118 | closed, |
| 1119 | out: () => out, |
| 1120 | type: (text) => ws.send(Buffer.from(text)), |
| 1121 | until: (re, ms = 30_000) => until(`${re} in the terminal (got ${JSON.stringify(out.slice(-300))}, closed ${JSON.stringify(closedWith)})`, async () => re.test(out), ms), |
| 1122 | }), |
| 1123 | ); |
| 1124 | }); |
| 1125 | } |
| 1126 | |
| 1127 | test("a web terminal: only its opener attaches, the sandbox API can't reach it, and End takes it away", async () => { |
| 1128 | const me = await ok("GET", "/user"); |
| 1129 | const owner = me.login; |
| 1130 | await ok("POST", "/user/repos", { name: "term-demo" }); |
| 1131 | await ok("PUT", `/repos/${owner}/term-demo/contents/README.md`, { message: "init", content: Buffer.from("# term\n").toString("base64") }); |
| 1132 | assert.equal((await asPerson("POST", "/diffinery/agents", { login: "term-bot", name: "Term Bot" })).status, 201); |
| 1133 | const page = (path) => fetch(`${base}/${owner}/term-demo/${path}`).then(async (r) => ({ status: r.status, text: await r.text(), headers: r.headers })); |
| 1134 | async function form(path, fields, headers = {}) { |
| 1135 | const res = await fetch(`${base}/${owner}/term-demo/terminals`, { headers }); |
| 1136 | const csrf = /name="_csrf" value="([^"]+)"/.exec(await res.text())?.[1]; |
| 1137 | const cookie = /dfy_csrf=([^;]+)/.exec(res.headers.get("set-cookie") ?? "")?.[1]; |
| 1138 | return fetch(`${base}/${owner}/term-demo/${path}`, { method: "POST", redirect: "manual", headers: { ...headers, cookie: [headers.cookie, `dfy_csrf=${cookie}`].filter(Boolean).join("; "), "sec-fetch-site": "same-origin" }, body: new URLSearchParams({ _csrf: csrf ?? "", ...fields }) }); |
| 1139 | } |
| 1140 | |
| 1141 | // The notice comes first, and it is a Kumo checkbox, not a native one. |
| 1142 | const list = await page("terminals"); |
| 1143 | assert.equal(list.status, 200); |
| 1144 | assert.match(list.text, /Open a terminal/); |
| 1145 | assert.match(list.text, /my own Anthropic or OpenAI account/); |
| 1146 | assert.ok(!/<input[^>]+type="checkbox"/.test(list.text.replace(/<input[^>]+data-k[^>]*>/g, "")), "no native checkbox"); |
| 1147 | const refused = await form("terminals", { agent: "term-bot", ref: "main" }); |
| 1148 | assert.equal(refused.status, 422); |
| 1149 | assert.match(await refused.text(), /accept the notice first/); |
| 1150 | const opened = await form("terminals", { agent: "term-bot", ref: "main", accept: "1" }); |
| 1151 | assert.equal(opened.status, 303, await opened.text()); |
| 1152 | const path = new URL(opened.headers.get("location"), base).pathname; |
| 1153 | const id = path.split("/").pop(); |
| 1154 | const running = await until("the terminal to start", async () => { |
| 1155 | const p = await page(`terminals/${id}`); |
| 1156 | return p.text.includes("data-socket") ? p : null; |
| 1157 | }); |
| 1158 | assert.match(running.text, /Start Claude Code/); |
| 1159 | assert.match(running.text, /Start Codex/, "a private repository offers Codex"); |
| 1160 | assert.match(running.text, /\/-\/terminal\/[a-z0-9]+\.js/); |
| 1161 | const sandboxId = poolSandboxes()[0]; |
| 1162 | |
| 1163 | // The socket: this site's Origin, a browser session, and only the opener. |
| 1164 | const url = `${base.replace("http", "ws")}/${owner}/term-demo/terminals/${id}/socket?cols=100&rows=30`; |
| 1165 | const origin = new URL(base).origin; |
| 1166 | assert.equal((await termSocket(url, {})).status, 403, "no Origin"); |
| 1167 | assert.equal((await termSocket(url, { origin: "https://evil.example" })).status, 403, "another Origin"); |
| 1168 | assert.equal((await termSocket(url, { origin, authorization: `Bearer ${token}` })).status, 403, "a token, even the opener's own admin token"); |
| 1169 | assert.equal((await termSocket(url, { origin, cookie: `__Host-dfy_session=${RIVAL_SESSION}` })).status, 404, "another person"); |
| 1170 | const t = await termSocket(url, { origin }); |
| 1171 | assert.equal(t.status, 101, JSON.stringify(t)); |
| 1172 | t.type("stty size; echo \"s=[$DIFFINERY_SANDBOX_SECRET] t=[$DIFFINERY_JOB_TOKEN]\"; git rev-parse --abbrev-ref HEAD; echo hi-$((6*7))\n"); |
| 1173 | await t.until(/hi-42/); |
| 1174 | assert.match(t.out(), /30 100/); |
| 1175 | assert.match(t.out(), /s=\[\] t=\[\]/); |
| 1176 | assert.match(t.out(), /\bmain\b/); |
| 1177 | |
| 1178 | // Another person, even one the owner made an admin of the repository, sees nothing of it. |
| 1179 | const invite = await ok("PUT", `/repos/${owner}/term-demo/collaborators/rival`, { permission: "admin" }); |
| 1180 | if (invite?.id) await fetch(`${base}/api/v3/user/repository_invitations/${invite.id}`, { method: "PATCH", headers: { cookie: `__Host-dfy_session=${RIVAL_SESSION}`, "sec-fetch-site": "same-origin" } }); |
| 1181 | const rival = { cookie: `__Host-dfy_session=${RIVAL_SESSION}` }; |
| 1182 | assert.equal((await fetch(`${base}/${owner}/term-demo/terminals/${id}`, { headers: rival })).status, 404); |
| 1183 | assert.ok(!(await (await fetch(`${base}/${owner}/term-demo/terminals`, { headers: rival })).text()).includes(id)); |
| 1184 | assert.equal((await form(`terminals/${id}/end`, {}, rival)).status, 404); |
| 1185 | assert.equal((await termSocket(url, { origin, ...rival })).status, 404); |
| 1186 | |
| 1187 | // The sandbox API and MCP never reach a terminal's sandbox, not even for a site admin's admin token. |
| 1188 | assert.equal((await api("POST", `/repos/${owner}/term-demo/diffinery/sandboxes/${sandboxId}/exec`, { cmd: "cat ~/.claude/.credentials.json" })).status, 404); |
| 1189 | assert.equal((await api("POST", `/repos/${owner}/term-demo/diffinery/sandboxes/${sandboxId}/read`, { path: "/root/.codex/auth.json" })).status, 404); |
| 1190 | assert.equal((await api("POST", `/repos/${owner}/term-demo/diffinery/sandboxes/${sandboxId}/close`)).status, 404); |
| 1191 | const viaMcp = await mcp("sandbox_exec", { owner, repo: "term-demo", sandbox_id: sandboxId, command: "id" }); |
| 1192 | assert.ok(viaMcp?.isError, JSON.stringify(viaMcp)); |
| 1193 | |
| 1194 | // Limits: two open per repository. |
| 1195 | const second = await form("terminals", { agent: "term-bot", ref: "main" }); |
| 1196 | assert.equal(second.status, 303); |
| 1197 | const third = await form("terminals", { agent: "term-bot", ref: "main" }); |
| 1198 | assert.equal(third.status, 422); |
| 1199 | assert.match(await third.text(), /2 terminals open in this repository/); |
| 1200 | const secondId = new URL(second.headers.get("location"), base).pathname.split("/").pop(); |
| 1201 | |
| 1202 | // End: the socket closes, the sandbox and its git credential go, and it can't be attached again. |
| 1203 | assert.equal((await form(`terminals/${id}/end`, {})).status, 303); |
| 1204 | const closed = await t.closed; |
| 1205 | assert.ok([1000, 1006, 1011].includes(closed.code), JSON.stringify(closed)); |
| 1206 | assert.equal((await termSocket(url, { origin })).status, 409); |
| 1207 | assert.match((await page(`terminals/${id}`)).text, /You ended it/); |
| 1208 | await until("the pool to stop the sandbox", async () => !poolSandboxes().includes(sandboxId) || (await fetch(`${base}/${owner}/term-demo/terminals/${id}`)).ok); |
| 1209 | |
| 1210 | // Losing access ends a terminal too: the agent's write access goes, and the next check ends it. |
| 1211 | await until("the second terminal to start", async () => (await page(`terminals/${secondId}`)).text.includes("data-socket")); |
| 1212 | assert.equal((await api("DELETE", "/diffinery/agents/term-bot")).status, 204); |
| 1213 | await until("the second terminal to end", async () => /no longer have write access|ended/i.test((await page(`terminals/${secondId}`)).text) && !(await page(`terminals/${secondId}`)).text.includes("data-socket"), 150_000); |
| 1214 | }); |