diff --git a/README.md b/README.md index 2e73510..e3fc099 100644 --- a/README.md +++ b/README.md @@ -450,7 +450,7 @@ npx -y spacesheep@latest skills lint --json # for CI: exits 1 when the fold | `spacesheep mcp status \| uninstall` | Which harnesses go through it; take it out of them | | `spacesheep logout` | Forget the stored key | | `spacesheep whoami` | Who the current key belongs to | -| `spacesheep deploy [dir\|file]` | Publish. Options: `--space`, `--new`, `--title`, `--slug`, `--emoji`, `--description`, `--visibility`, `--team`, `--team-access`, `--no-team`, `--org`, `--base `, `--replace`, `-m `, `--json`. A folder's `.spacesheep.json` pins it to one space; if `index.html`'s `` no longer matches the page the pin last published, deploy stops and asks for `--space` (update it anyway) or `--new` (a new space). Every deploy prints where the space lives (a team, or personal). Each update names the version its files are built on (`base_sha`: what this folder last published or read on this machine, or `--base`), so anything published since is merged in rather than overwritten. After a merge the folder keeps its base, so the next deploy merges the server's part in again. A clash is refused with the live version's sha and how to keep both (`read -o`, change, deploy); `--replace` publishes over it, erasing the changes made there. | +| `spacesheep deploy [dir\|file]` | Publish. Options: `--space`, `--new`, `--title`, `--slug`, `--emoji`, `--description`, `--visibility`, `--team`, `--team-access`, `--no-team`, `--org`, `--base <sha>`, `--replace`, `-m <version name>`, `--json`. A folder's `.spacesheep.json` pins it to one space; if `index.html`'s `<title>` no longer matches the page the pin last published, deploy stops and asks for `--space` (update it anyway) or `--new` (a new space). Every deploy prints where the space lives (a team, or personal). Each update names the version its files are built on (`base_sha`: what this folder last published or read on this machine, or `--base`), so anything published since is merged in rather than overwritten. After a merge the folder keeps its base, so the next deploy merges the server's part in again. A clash is refused with the live version's sha and how to keep both (`read -o`, change, deploy); `--replace` (or `--base latest`, the live version itself) publishes over it, erasing the changes made there. A folder's `.spacesheep.json` from the /sheep skill (`uuid`, `deployed_sha`) pins the space too, and its `deployed_sha` is the base when it is newer than this machine's. With no base at all, onto a space another session or person published last, deploy reads the live version before uploading anything: the same files are reported as already live (nothing deployed), different ones stop with who published it and the three ways on. No refusal is ever sent again by the CLI (`rate_limited` once, after a short `retry_after`); each prints the server's words and one line on what to do. Exit codes: 1 failed or refused, 2 wrong command line, 3 not signed in, 4 `stop_retrying` (the server refuses that call until something changes: don't run it again). | | `spacesheep list` | Your spaces | | `spacesheep read <space> [path] [-o dir]` | Print a space's files, or save them to a folder byte for byte. A whole space saved to a folder is the newest version, and a deploy from that folder builds on it. | | `spacesheep versions <space>` | Version history | diff --git a/bin/spacesheep.js b/bin/spacesheep.js index 5dfa09e..32bf97f 100755 --- a/bin/spacesheep.js +++ b/bin/spacesheep.js @@ -41,6 +41,14 @@ const os = require("os"); const { deviceLogin, connectWithKey, redeemCode, agentClient } = require("../lib/login"); const { deploy } = require("../lib/deploy"); const { updateNotice, selfUpdate } = require("../lib/update"); +const { refusalOf, EXIT_STOP_RETRYING } = require("../lib/refusals"); +/** `call`'s refusal, from the tool's first text block. */ +function callRefusal(result) { + const text = (result.content || []).filter((c) => c.type === "text").map((c) => c.text).join("\n"); + let v = text; + try { v = JSON.parse(text); } catch {} + return refusalOf(v); +} const HELP = ` spacesheep ${pkg.version} — publish web pages to spacesheep.dev from a terminal or CI @@ -159,8 +167,16 @@ const HELP = ` -m, --message <text> version name shown in the space's history --base <sha> the version your files are built on, or the start of its sha: anything published since is merged in (default: what this folder last published - or read on this machine) + or read on this machine, or its .spacesheep.json's deployed_sha) + --base latest the live version itself: nothing is merged, your files replace it + (the same as --replace) --replace publish over the live version on purpose, erasing changes made there + A folder with no base, onto a space someone else published last, stops + before uploading (or says the same files are already live). + + Exit codes + 0 done 1 failed or refused 2 wrong command line 3 not signed in + 4 stop_retrying: the server refuses this call until something changes — don't run it again --json print the server's JSON result Auth @@ -290,6 +306,12 @@ const commands = { async deploy(opts) { const r = await deploy(client(), opts._[0], { ...opts, via: process.env.GITHUB_ACTIONS ? "GitHub Actions" : "CLI" }, log); if (opts.json) return out(r); + if (r.unchanged) { + log(`\n = Already live: these files are the live version of ${r.url || r.uuid} (${String(r.sha).slice(0, 12)}, published by ${r.who}). Nothing was deployed; this folder now builds on that version.`); + out(r.url || r.uuid); + if (process.env.GITHUB_OUTPUT) fs.appendFileSync(process.env.GITHUB_OUTPUT, `url=${r.url || ""}\nuuid=${r.uuid}\nsha=${r.sha}\n`); + return; + } log(`\n ✓ ${r.is_update ? "Updated" : "Created"} ${r.url}`); // Every push says who can read it because of where it lives, team or personal. if (r.lives_in) log(` ⌂ Lives in ${r.lives_in}${r.team_from && !r.is_update ? ` (team from ${r.team_from === "--team" ? "--team" : path.relative(process.cwd(), r.team_from) || ".spacesheep.json"})` : ""}`); @@ -300,7 +322,7 @@ const commands = { const m = r.merged, merged = m.merged || [], kept = m.kept || []; log(` ⇄ Merged with what was published since your version (${String(m.base_sha || "").slice(0, 12)} → ${String(m.server_sha || "").slice(0, 12)}): ${merged.length} file(s) merged${merged.length ? ` (${merged.slice(0, 5).join(", ")}${merged.length > 5 ? ", …" : ""})` : ""}, ${kept.length} kept as they are on the server. Read the page back before saying what it says. This folder doesn't have the server's part, so the next deploy from it merges that in again (spacesheep read ${r.uuid || "<space>"} -o <folder> brings it here).`); } - if (r.replaced) log(` ! Replaced the live version ${String(r.replaced).slice(0, 12)} on purpose (--replace).`); + if (r.replaced) log(` ! Replaced the live version ${String(r.replaced).slice(0, 12)} on purpose (${r.base_latest ? "--base latest" : "--replace"}).`); if (r.team_unchanged) log(` ! ${r.team_from === "--team" ? "--team names" : `${path.relative(process.cwd(), r.team_from || "") || ".spacesheep.json"} names`} a team this space isn't in. A deploy never moves a live space, so nothing moved: move it from the space's Share → Lives in, or check you are publishing the page you mean.`); for (const w of r.warnings || []) log(` ! ${w}`); if (r.metadata_warning) log(` ! ${r.metadata_warning.split(".")[0]}. Pass --emoji and --description.`); @@ -379,9 +401,10 @@ const commands = { catch (e) { if (/not found|unknown tool/i.test(e.message)) e.message += " — `spacesheep tools` lists the tools"; throw e; } const shown = t.render(name, result, opts); if (opts.json) out(shown.json); - else if (result.isError) { const e = new Error(shown.text || `${name} failed`); e.code = "ETOOL"; throw e; } - else if (shown.text) out(shown.text); - if (result.isError) process.exitCode = 1; + const refusal = result.isError ? callRefusal(result) : null; + if (opts.json) { if (result.isError) process.exitCode = refusal && refusal.code === "stop_retrying" ? EXIT_STOP_RETRYING : 1; return; } + if (result.isError) { const e = new Error(shown.text || `${name} failed`); e.code = "ETOOL"; if (refusal) e.refusal = refusal; throw e; } + if (shown.text) out(shown.text); }, async feedback(opts) { const args = require("../lib/inspection").feedbackArgs(opts); @@ -616,7 +639,10 @@ async function door(argv) { await commands[cmd](opts); if (!opts.json && cmd !== "update") { const n = await updateNotice(); if (n) log(`\n${n}`); } } catch (e) { - console.error(`\n ✗ ${e.message}\n`); - process.exit(e.code === "EAUTH" ? 3 : 1); + // A refusal is never run again here: its words, the one line on what to do, and an + // exit code of its own for stop_retrying (lib/refusals.js). + const { errorWords, exitCodeFor } = require("../lib/refusals"); + console.error(`\n ✗ ${errorWords(e, { space: opts.space || (["read", "versions", "share", "delete"].includes(cmd) ? opts._[0] : undefined) })}\n`); + process.exit(exitCodeFor(e)); } })(); diff --git a/lib/bases.js b/lib/bases.js index 2821099..b446408 100644 --- a/lib/bases.js +++ b/lib/bases.js @@ -58,6 +58,13 @@ function savedBase(where) { return hit && typeof hit.sha === "string" && hit.sha ? hit.sha : null; } +/** When the saved base was saved (ISO time), or null: weighed against a .spacesheep.json's + * deployed_at, which the /sheep skill writes beside its deployed_sha. */ +function savedAt(where) { + const hit = hitOf(where); + return hit && typeof hit.sha === "string" && hit.sha && typeof hit.at === "string" ? hit.at : null; +} + /** The merged version a deploy from `dir` made when no base for it was known, or null: * the folder lacks part of what is live, and nothing says what it is built on. */ function heldBase(where) { @@ -98,4 +105,4 @@ function write(where, rec) { } catch {} } -module.exports = { savedBase, saveBase, heldBase, holdBase, mergedInto, bareName }; +module.exports = { savedBase, savedAt, saveBase, heldBase, holdBase, mergedInto, bareName }; diff --git a/lib/deploy.js b/lib/deploy.js index 6d2deac..a0d6000 100644 --- a/lib/deploy.js +++ b/lib/deploy.js @@ -7,7 +7,8 @@ const fs = require("fs"); const path = require("path"); const crypto = require("crypto"); const { collectSession } = require("./session"); -const { savedBase, saveBase, heldBase, holdBase, mergedInto, bareName } = require("./bases"); +const { savedBase, savedAt, saveBase, heldBase, holdBase, mergedInto, bareName } = require("./bases"); +const { refusalOf } = require("./refusals"); const SKIP_DIRS = new Set(["node_modules", ".git", ".wrangler", ".claude"]); // The file cap is the SERVER's, per plan, and stage_begin answers with the caps of @@ -54,11 +55,19 @@ function preflightError(begin) { * the refusal as a result printed "Created undefined". */ function refusalError(result, what) { if (result && typeof result === "object" && typeof result.error === "string") { - const err = new Error(`${what} refused — ${result.error}: ${result.message || "no message"}${result.retry_after ? ` (retry in ${result.retry_after}s)` : ""}`); + // stop_retrying is the server's last word on a call sent again and again: as it wrote it. + const err = new Error(result.error === "stop_retrying" && result.message ? result.message + : `${what} refused — ${result.error}: ${result.message || "no message"}${result.retry_after ? ` (retry in ${result.retry_after}s)` : ""}`); err.code = "EREFUSED"; + err.refusal = refusalOf(result); + return err; + } + if (typeof result === "string") { + const err = Object.assign(new Error(`${what} failed: ${result.slice(0, 500)}`), { code: "EREFUSED" }); + const r = refusalOf(result); + if (r) err.refusal = r; return err; } - if (typeof result === "string") return Object.assign(new Error(`${what} failed: ${result.slice(0, 500)}`), { code: "EREFUSED" }); return null; } @@ -276,7 +285,99 @@ function clashWords(refusal, again, space, merged, said = "") { const isClash = (info) => !!info && (info.error === "conflict" || info.code === "conflict" || (info.violations || []).some((v) => v && v.field === "parent")); +// ---------------------------------------------------------------- a deploy that names no base +// A folder with no version of the space to build on (none saved on this machine, no +// deployed_sha in its .spacesheep.json) sends no base_sha, and the server refuses it when +// someone else wrote the live version. Agents ran that refused deploy again and again (one +// space, two Claude Code sessions on two Macs, ~500 times a day for two weeks), uploading +// the site each time. So before any upload the CLI reads who wrote the live version, the +// server's way (packages/mcp/src/deploy-base.ts), and what its files are: the same files +// are already live, and different ones stop here with the three ways on. + +/** A live link's placeholder: nothing anyone wrote, so the server publishes over it. */ +const LIVE_LINK_VERSION_NAME = "Live link started"; +const MCP_VIAS = new Set(["mcp", "automation"]); +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** A list_versions row against this caller (its `session`): "mine", "other" (certainly not + * this caller, as the server judges it), or "unsure" (the server decides). Only versions the + * caller's own account pushed carry `pushed_by`; a door other than MCP is never a CLI's. */ +function writerOf(row, me) { + if (!MCP_VIAS.has(String(row.via || "").toLowerCase())) return "other"; + const p = row.pushed_by; + if (!p || typeof p !== "object") return "other"; + const a = String(p.session_id || "").trim().toLowerCase(); + const b = String((me && me.session_id) || "").trim().toLowerCase(); + if (a && b) return a === b ? "mine" : "other"; + return "unsure"; +} + +/** Who wrote a version, in words: "another session (Claude Code on mac-2, session …)". */ +function writerWords(row) { + const via = String(row.via || "").toLowerCase(); + if (!MCP_VIAS.has(via)) { + const doors = { viewer: "Shepherd", edit: "an edit in the browser", dashboard: "the dashboard agent", tg: "the Telegram agent", work: "the work board", memory: "the memory board" }; + return doors[via] || (via ? `the ${via} path` : "someone else"); + } + const p = row.pushed_by; + if (!p || typeof p !== "object") return "someone else (another account)"; + const where = [p.label, p.machine && `on ${p.machine}`].filter(Boolean).join(" "); + const bits = [where, p.session_id && `session ${p.session_id}`].filter(Boolean).join(", "); + return `another session${bits ? ` (${bits})` : ""}`; +} + +/** The live version's files as path → staged sha, from list_files, or null when they + * can't be read (an older server, a viewer): then the server decides, as before. */ +async function liveFiles(client, space, sha) { + const files = new Map(); + let after; + for (let page = 0; page < 100; page++) { + const args = { [UUID_RE.test(space) ? "space_id" : "space"]: space, version: sha, limit: 200 }; + if (after) args.after = after; + const r = await client.call("list_files", args).catch(() => null); + if (!r || typeof r !== "object" || !Array.isArray(r.files)) return null; + for (const f of r.files) if (f && typeof f.path === "string") files.set(f.path, typeof f.staged_sha === "string" ? f.staged_sha : null); + after = r.page && r.page.next; + if (!after) return files; + } + return null; +} + +/** For a deploy onto `space` that names no base: null when the server would build it on + * this caller's own version (or might: it decides), else the live version — its sha, who + * wrote it, and whether its files are exactly `files` (each with its staged `sha`). */ +async function liveCheck(client, space, files, me) { + const r = await client.call("list_versions", { uuid: space, limit: 50 }).catch(() => null); + const rows = r && typeof r === "object" && Array.isArray(r.versions) ? r.versions.filter((v) => v && typeof v === "object") : []; + const head = rows.find((v) => v.latest) || rows[0]; + // Today's rows name `sha`, `via` and `pushed_by`; a shape without them says nothing about who. + if (!head || typeof head.sha !== "string" || !head.sha) return null; + if (String(head.via || "").toLowerCase() === "blank" || head.name === LIVE_LINK_VERSION_NAME) return null; + if (rows.some((v) => writerOf(v, me) !== "other")) return null; + const live = await liveFiles(client, space, head.sha); + if (!live) return null; + const same = live.size === files.length && files.every((f) => live.get(f.path) === f.sha); + const id = r.space && typeof r.space.uuid === "string" && r.space.uuid ? r.space.uuid : null; + return { sha: head.sha, who: writerWords(head), same, id }; +} + +/** The stop for a folder with no base onto a space someone else published last. */ +function liveElsewhere(live, space, dir) { + const folder = path.relative(process.cwd(), dir) || "."; + const err = new Error(`The live version (${live.sha.slice(0, 12)}) was published by ${live.who}, and this folder has no version of ${space} to build on, so nothing was uploaded or deployed. Pull it first with \`spacesheep read ${space} -o <dir>\` and merge your changes into that folder, then deploy from it; or re-run with --base <sha> (the version your files came from) to merge onto it; or with --replace (the same as --base latest) to replace it, erasing what was published there: spacesheep deploy ${folder} --space ${space} --replace`); + err.code = "EREFUSED"; + err.refusal = { code: "conflict", message: err.message, local: true }; + err.space = space; + return err; +} + +/** A .spacesheep.json's deployed_sha (the /sheep skill writes it beside `uuid`), when it is a sha. */ +const pinnedSha = (m) => (typeof m.deployed_sha === "string" && /^[0-9a-f]{7,64}$/i.test(m.deployed_sha) ? m.deployed_sha : null); + async function deploy(client, target, opts, log) { + // --base latest: the live version's own sha, read just before the deploy. A base that IS + // the live version merges nothing: the files sent become the live version (--replace). + if (opts.base === "latest") opts = { ...opts, base: undefined, replace: true, latest: true }; const { dir, files } = collect(path.resolve(target || ".")); if (!files.length) throw new Error(`nothing to deploy in ${dir}`); if (!files.some((f) => f.path === "index.html")) { @@ -294,8 +395,11 @@ async function deploy(client, target, opts, log) { // --new: the page is its own document — no pin, and none of the pinned space's // metadata carried over to it. const pin = opts.new ? {} : manifest; - const uuid = opts.space || pin.space || undefined; - if ((opts.replace || opts.base) && !uuid) throw new Error(`${opts.replace ? "--replace" : "--base"} is for updating a space, and this deploy makes a new one. Pass --space <uuid|url>, or deploy from the folder that published it.`); + // The /sheep skill pins a folder with `uuid` (and its deployed_sha); this CLI with `space`. + const pinSpace = pin.space || (typeof pin.uuid === "string" && pin.uuid) || undefined; + const uuid = opts.space || pinSpace || undefined; + const flag = opts.latest ? "--base latest" : opts.replace ? "--replace" : "--base"; + if ((opts.replace || opts.base) && !uuid) throw new Error(`${flag} is for updating a space, and this deploy makes a new one. Pass --space <uuid|url>, or deploy from the folder that published it.`); if (opts.replace && opts.base) throw new Error("--replace and --base both name the version yours is built on: pass one"); if (opts.base !== undefined && typeof opts.base !== "string") throw new Error("--base needs a version's sha (spacesheep versions <space>)"); const given = opts.base && await fullVersion(client, uuid, opts.base); @@ -305,9 +409,21 @@ async function deploy(client, target, opts, log) { // kept sending the version read, and the second deploy from the folder clashed with the // first. The base is the newest record under any of them: a read by @handle/slug after a // deploy is newer than the deploy's. - const names = uuid && [pin.space, pin.url].some((n) => n && bareName(n) === bareName(uuid)) ? [uuid, pin.space, pin.url] : [uuid]; + const pinIsSpace = !!uuid && [pinSpace, pin.url].some((n) => n && bareName(n) === bareName(uuid)); + const names = pinIsSpace ? [uuid, pinSpace, pin.url] : [uuid]; const where = { origin: client.url, space: names, dir }; - const held = uuid && !opts.replace && !opts.base ? heldBase(where) : null; + // What this folder's files are built on when nothing names it: the newer of the version + // saved on this machine and the pin's deployed_sha (the /sheep skill's record, kept in the + // folder), so a folder the skill published updates onto that version, not with no base. + let ownBase = null, merged = null; + if (uuid && !opts.replace && !opts.base) { + const saved = savedBase(where); + const pinned = pinIsSpace ? pinnedSha(pin) : null; + const pinnedNewer = pinned && (!saved || (typeof pin.deployed_at === "string" && savedAt(where) && pin.deployed_at > savedAt(where))); + if (pinnedNewer) ownBase = pinned; + else if (saved) { ownBase = saved; merged = mergedInto(where); } + } + const held = uuid && !opts.replace && !opts.base && !ownBase ? heldBase(where) : null; if (held) throw new Error(`the last deploy from this folder was merged with changes made on the server, into version ${held}, and this folder doesn't have them. The server didn't say which version the merge was built on, so a deploy from here could erase them. Nothing was deployed. To keep them: spacesheep read ${uuid} -o <folder>, put your changes in, then spacesheep deploy <folder> --space ${uuid}. To publish this folder over them, erasing them: --replace.`); // Started before the uploads and awaited after them, so it costs no wall time. @@ -321,6 +437,29 @@ async function deploy(client, target, opts, log) { if (uuid) beginArgs.space = uuid; if (wantsPreflight(files)) log(` checking ${files.length.toLocaleString("en-US")} files with the server before uploading…`); for (const f of files) f.sha = stagedSha(f.path, fs.readFileSync(f.abs)); + // No base for an update: who wrote the live version, before a single upload. + let liveSame = null; + if (uuid && !opts.replace && !opts.base && !ownBase) { + const live = await liveCheck(client, uuid, files, await sessionP); + if (live && !live.same) throw liveElsewhere(live, uuid, dir); + if (live) liveSame = live; + } + // The same files are live already: a deploy would add nothing but a version. With new + // metadata it goes out, built on the live version (nothing in it is lost). + const metaAsked = ["title", "slug", "emoji", "description", "visibility", "org", "team", "teamAccess", "skill"].some((k) => opts[k] !== undefined && opts[k] !== false); + if (liveSame && !metaAsked) { + const id = liveSame.id || (UUID_RE.test(uuid) ? uuid : null); + saveBase({ ...where, space: [...names, id].filter(Boolean) }, liveSame.sha); + const url = (pinIsSpace && pin.url) || (/^https?:\/\//.test(uuid) ? uuid : null); + if (!opts.noManifest && id) { + const next = { ...pin, space: id }; + if (url) next.url = url; + if (title) next.page_title = title; + if (pinnedSha(pin)) { next.deployed_sha = liveSame.sha; next.deployed_at = new Date().toISOString(); } + fs.writeFileSync(manifestPath(dir), JSON.stringify(next, null, 2) + "\n"); + } + return { unchanged: true, uuid: id || uuid, url, sha: liveSame.sha, who: liveSame.who }; + } beginArgs.files = files.map((f) => ({ path: f.path, size: f.size, sha: f.sha })); const begin = await client.call("stage_begin", beginArgs); // The preflight's list names every wall at once; the plain cap check is for a @@ -357,11 +496,11 @@ async function deploy(client, target, opts, log) { // The version these files are built on: --base, the newest one read just now // (--replace), else what this folder was last published as from this machine. With // none, the server works it out from who wrote the live version. - let base = null, merged = null; + let base = null; if (uuid) { if (opts.replace) base = await newestVersion(client, uuid); else if (opts.base) base = given; - else { base = savedBase(where); merged = mergedInto(where); } + else base = ownBase || (liveSame && liveSame.sha) || null; } if (base) args.base_sha = base; const again = `spacesheep deploy ${path.relative(process.cwd(), dir) || "."}${opts.space ? ` --space ${opts.space}` : ""}`; @@ -377,11 +516,13 @@ async function deploy(client, target, opts, log) { }); } catch (e) { if (e && e.info && isClash(e.info)) e.message = clashWords(e.info, again, uuid, merged, e.message); + if (e && typeof e === "object") e.space = uuid; throw e; } const refused = refusalError(result, "deploy"); if (refused) { if (isClash(result)) refused.message = clashWords(result, again, uuid, merged, refused.message); + refused.space = uuid; throw refused; } const id = result.uuid || result.id || result.space_id; @@ -399,11 +540,18 @@ async function deploy(client, target, opts, log) { else holdBase(after, result.sha); } else if (id && result.sha) saveBase(after, result.sha); if (opts.replace && base && !result.merged) result.replaced = base; + if (opts.latest) result.base_latest = true; if (id && !opts.noManifest) { const next = { ...pin, space: id }; if (result.url) next.url = result.url; // What this folder last published, so the next run can tell a different page. if (title) next.page_title = title; else delete next.page_title; + // A pin that keeps deployed_sha (the /sheep skill's) keeps it current, as bases.json is: + // the version this folder's files are (after a merge, the version the merge was built on). + if (pinnedSha(pin)) { + const ownSha = result.merged ? (typeof result.merged === "object" && result.merged.base_sha) || base : result.sha; + if (ownSha) { next.deployed_sha = ownSha; next.deployed_at = new Date().toISOString(); } + } // Where its space lives, read back from the server, so the next new page from // this folder (--new) goes to the same team. if (result.team && result.team.id) next.team = { id: result.team.id, name: result.team.name }; @@ -420,4 +568,4 @@ async function deploy(client, target, opts, log) { return result; } -module.exports = { teamFor, deploy, clashWords, newestVersion, newestOf, collect, fileCapError, FALLBACK_MAX_FILES, pageTitle, pinMismatch, stagedSha, preflightError, refusalError, stageAll, wantsPreflight }; +module.exports = { teamFor, deploy, clashWords, liveCheck, writerOf, writerWords, newestVersion, newestOf, collect, fileCapError, FALLBACK_MAX_FILES, pageTitle, pinMismatch, stagedSha, preflightError, refusalError, stageAll, wantsPreflight }; diff --git a/lib/doors.js b/lib/doors.js index dfd86ae..1ead1fc 100644 --- a/lib/doors.js +++ b/lib/doors.js @@ -618,10 +618,18 @@ async function run(found, argv, ctx) { return 1; } if (!resp.ok) { + // Never sent again from here: a refusal is the same refusal the next time (lib/refusals.js). const info = errorInfo(resp.status, text); + const ref = require("./refusals"); + const r = ref.refusalOf(info); + const stop = r && r.code === "stop_retrying"; if (parsed.global.json) out(JSON.stringify(info, null, 2)); - else err(`\n ✗ ${refusalWords(info, { word: true })}\n`); - return 1; + else if (stop) err(`\n ✗ ${info.message}\n ${ref.nextStep(r)}\n`); + else { + const step = ref.isFinal(r) ? ref.nextStep(r, { space: [parsed.inputs && parsed.inputs.space, parsed.inputs && parsed.inputs.space_id].find((v) => typeof v === "string") }) : null; + err(`\n ✗ ${refusalWords(info, { word: true })}${step ? `\n ${step}` : ""}\n`); + } + return stop ? ref.EXIT_STOP_RETRYING : 1; } if (parsed.global.json) { if (text) out(text.replace(/\n$/, "")); return 0; } if (!text) return 0; diff --git a/lib/mcp.js b/lib/mcp.js index 54f6510..b884b8c 100644 --- a/lib/mcp.js +++ b/lib/mcp.js @@ -4,6 +4,7 @@ "use strict"; const PROTOCOL = "2025-06-18"; +const { refusalOf, MAX_RATE_WAIT_S } = require("./refusals"); class McpClient { constructor(origin, key) { @@ -12,6 +13,7 @@ class McpClient { this.session = null; this.nextId = 1; this.ready = null; + this.sleep = (ms) => new Promise((r) => setTimeout(r, ms)); } async _post(body) { @@ -99,19 +101,31 @@ class McpClient { return tools; } - /** Call a tool and return its first text block, JSON-parsed when it parses. */ - async call(name, args = {}) { + /** Call a tool and return its first text block, JSON-parsed when it parses. A refusal + * (lib/refusals.js) is never sent again, except `rate_limited` once, after its + * retry_after when that is short. */ + async call(name, args = {}, { retried = false } = {}) { const result = await this.callRaw(name, args); const text = (result.content || []).filter((c) => c.type === "text").map((c) => c.text).join("\n"); let value = text; try { value = JSON.parse(text); } catch {} + const refusal = result.isError ? refusalOf(value) + : value && typeof value === "object" && typeof value.error === "string" ? refusalOf(value) : null; + if (refusal && refusal.code === "rate_limited" && !retried && refusal.retry_after && refusal.retry_after <= MAX_RATE_WAIT_S) { + await this.sleep(refusal.retry_after * 1000); + return this.call(name, args, { retried: true }); + } if (result.isError) { // Today's tools refuse with {error}; a call's door with ErrorInfo {code, message, violations}, // kept whole as `info` for whoever goes by its code. const info = value && typeof value === "object" ? value : {}; - const err = new Error(typeof value === "string" ? value : info.error || (info.message && require("./doors").refusalWords(info)) || text); + // Today's {error, message}: both, so the words say why and not only the word. + const err = new Error(typeof value === "string" ? value + : typeof info.error === "string" ? (typeof info.message === "string" && info.message ? `${info.error}: ${info.message}` : info.error) + : (info.message && require("./doors").refusalWords(info)) || text); err.code = "ETOOL"; if (info.code) err.info = info; + if (refusal) err.refusal = refusal; throw err; } return value; diff --git a/lib/refusals.js b/lib/refusals.js new file mode 100644 index 0000000..cf15c71 --- /dev/null +++ b/lib/refusals.js @@ -0,0 +1,74 @@ +// A refusal is the server saying no on purpose: the same call again gets the same no. +// Production saw agents loop on them — one account's two Claude Code sessions published +// one space ~500 times a day for two weeks, each refused `conflict`, and 2,934 publishes +// refused because the space wasn't shared with the caller. So the CLI never retries one +// of these words by itself (rate_limited at most once, after its retry_after), and it +// exits non-zero with the server's words plus one line saying what has to change. +// `stop_retrying` is the server refusing a caller that sent the same refused call five +// times in ten minutes: its message is printed as it is, and the exit code is its own. +"use strict"; + +const NO_RETRY = new Set([ + "conflict", "error", "forbidden", "invalid", "would_drop_files", "index_shrunk", + "placeholder_page", "stop_retrying", "rate_limited", +]); +/** The exit code for `stop_retrying`: 1 is any failure, 2 a wrong command line, 3 no sign-in. */ +const EXIT_STOP_RETRYING = 4; +/** rate_limited waits once, for at most this long; a longer retry_after is the caller's to wait. */ +const MAX_RATE_WAIT_S = 60; + +/** The plain-text answer the deploy and edit tools give a caller who may not change the space. */ +const PERMISSION = /^You can't change this space\b|only its owner (?:and people|can change one)/; + +/** A refusal in any shape a tool answers with, as {code, message, retry_after?}, or null: + * today's JSON {error, message}, a door's ErrorInfo {code, message}, or the permission + * refusal's plain text. */ +function refusalOf(x) { + if (typeof x === "string") return PERMISSION.test(x) ? { code: "error", message: x, permission: true } : null; + if (!x || typeof x !== "object") return null; + const word = (v) => (typeof v === "string" && /^[a-z][a-z_]*$/.test(v) ? v : null); + const code = word(x.error) || word(x.code); + if (!code) return null; + const message = typeof x.message === "string" ? x.message : ""; + const r = { code, message }; + const wait = Number(x.retry_after); + if (wait > 0) r.retry_after = wait; + if (PERMISSION.test(message) || code === "permission_denied") r.permission = true; + return r; +} + +const isFinal = (r) => !!r && (NO_RETRY.has(r.code) || !!r.permission); + +/** The one line that says what the person (or their agent) must do instead of running + * the same command again. `space`: the space it was about, for the commands named. */ +function nextStep(r, { space } = {}) { + if (!r) return null; + const sp = space || "<space>"; + if (r.permission || r.code === "forbidden") return `What to do: ask the space's owner to share it with you with "Can edit", or publish your own copy with --new. Running this again is refused the same way.`; + switch (r.code) { + case "stop_retrying": return "What to do: stop — the server refuses this call until something changes. Tell the person what was refused and wait for them."; + case "conflict": return `What to do: merge first — spacesheep read ${sp} -o <folder>, put your changes in, deploy from that folder (or --base <sha> / --replace). The same deploy again is refused the same way.`; + case "would_drop_files": + case "index_shrunk": return "What to do: deploy the folder holding every file the space should keep (the built site, not a part of it). Removing them is the person's call: ask before publishing a smaller version."; + case "placeholder_page": return "What to do: put the real page in index.html, then deploy once."; + case "invalid": return "What to do: change what the message names; the same command again is refused the same way."; + case "rate_limited": return `What to do: wait${r.retry_after ? ` ${Math.ceil(r.retry_after)} s` : ""}, then run it once more — not in a loop.`; + case "error": return "What to do: read the message above and change what it names; the same command again is refused the same way."; + default: return null; + } +} + +/** The exit code for an error the CLI is about to die of. */ +const exitCodeFor = (e) => (e && e.refusal && e.refusal.code === "stop_retrying" ? EXIT_STOP_RETRYING : e && e.code === "EAUTH" ? 3 : 1); + +/** What the CLI prints for an error: stop_retrying's message as the server wrote it; any + * other refusal, the error's own words and the line saying what to do. */ +function errorWords(e, ctx = {}) { + const r = e && e.refusal; + if (e && e.space) ctx = { ...ctx, space: e.space }; + if (r && r.code === "stop_retrying") return `${r.message || e.message}\n ${nextStep(r, ctx)}`; + const step = r && isFinal(r) ? nextStep(r, ctx) : null; + return step && !e.message.includes(step) ? `${e.message}\n ${step}` : e.message; +} + +module.exports = { NO_RETRY, EXIT_STOP_RETRYING, MAX_RATE_WAIT_S, refusalOf, isFinal, nextStep, exitCodeFor, errorWords }; diff --git a/package.json b/package.json index e981866..9a5b7db 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "spacesheep", - "version": "1.39.0", + "version": "1.40.0", "description": "Publish web pages to spacesheep.dev from a terminal or CI: `npx spacesheep deploy ./dist`", "bin": { "spacesheep": "./bin/spacesheep.js" diff --git a/test/doors.test.js b/test/doors.test.js index 0bf70b4..7aa1d54 100644 --- a/test/doors.test.js +++ b/test/doors.test.js @@ -444,7 +444,8 @@ test("end to end: spacesheep <noun> <verb> against a server that serves the tabl // A message that is one of its violations isn't printed twice; the others still are. const one = await cli(["spaces", "get", "@james/plan"], env); assert.equal(one.code, 1); - assert.equal(one.err, "\n ✗ size: takes a whole number (invalid)\n path: is required\n\n"); + // A refusal says what to do instead of running it again (lib/refusals.js). + assert.equal(one.err, "\n ✗ size: takes a whole number (invalid)\n path: is required\n What to do: change what the message names; the same command again is refused the same way.\n\n"); const before = seen.length; const wrong = await cli(["spaces", "get", "--nope"], env); @@ -979,8 +980,8 @@ test("end to end: a tool's refusal prints its sentence, in either server's words try { // ErrorInfo as the MCP door sends it (pretty-printed JSON), with what each violation adds. assert.equal(await said(JSON.stringify({ code: "not_found", message: "No such space.", violations: [] }, null, 2)), "✗ No such space."); - assert.equal(await said(JSON.stringify({ code: "invalid", message: "Check the request.", violations: [{ field: "path", message: "at most 300 characters" }] }, null, 2)), "✗ Check the request.\n path: at most 300 characters"); - assert.equal(await said(JSON.stringify({ code: "invalid", message: "path: at most 300 characters", violations: [{ field: "path", message: "at most 300 characters" }] })), "✗ path: at most 300 characters"); + assert.equal(await said(JSON.stringify({ code: "invalid", message: "Check the request.", violations: [{ field: "path", message: "at most 300 characters" }] }, null, 2)), "✗ Check the request.\n path: at most 300 characters\n What to do: change what the message names; the same command again is refused the same way."); + assert.equal(await said(JSON.stringify({ code: "invalid", message: "path: at most 300 characters", violations: [{ field: "path", message: "at most 300 characters" }] })), "✗ path: at most 300 characters\n What to do: change what the message names; the same command again is refused the same way."); // Today's tools: {error}, or plain words. assert.equal(await said('{"error":"Space not found."}'), "✗ Space not found."); assert.equal(await said("Space not found."), "✗ Space not found."); diff --git a/test/refusal-loops.test.js b/test/refusal-loops.test.js new file mode 100644 index 0000000..dbcfe98 --- /dev/null +++ b/test/refusal-loops.test.js @@ -0,0 +1,282 @@ +"use strict"; +// Agents looped on publish refusals: two Claude Code sessions on two Macs published one +// space ~500 times a day, each refused `conflict` (no base, someone else's live version), +// and 2,934 publishes were refused for a space never shared with the caller. A deploy with +// no base now looks before it uploads, and no refusal is ever sent again by the CLI. +const test = require("node:test"); +const assert = require("node:assert"); +const fs = require("fs"); +const os = require("os"); +const path = require("path"); +const http = require("http"); +const { spawn } = require("child_process"); + +const conf = fs.mkdtempSync(path.join(os.tmpdir(), "ss-loop-conf-")); +process.env.SPACESHEEP_CONFIG_DIR = conf; +const { deploy, stagedSha, writerOf } = require("../lib/deploy"); +const { savedBase } = require("../lib/bases"); +const { McpClient } = require("../lib/mcp"); +const refusals = require("../lib/refusals"); + +const ORIGIN = "https://mcp.example/mcp"; +const SPACE = "11111111-2222-4333-8444-555555555555"; +const HTML = "<html><head><title>Q3q3"; +const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "ss-loop-")); +function page(pin, html = HTML) { + const dir = tmp(); + fs.writeFileSync(path.join(dir, "index.html"), html); + if (pin) fs.writeFileSync(path.join(dir, ".spacesheep.json"), JSON.stringify(pin)); + return dir; +} +const pinOf = (dir) => JSON.parse(fs.readFileSync(path.join(dir, ".spacesheep.json"), "utf-8")); + +/** A deploy against a fake client: `answers` maps a tool to its answer (a function of the args, or a value). */ +async function run(dir, opts, answers, env = {}) { + const calls = []; + const client = { url: ORIGIN, call: async (name, args) => { + calls.push([name, args]); + if (name === "stage_begin") return { upload_url: "https://stage.example/u", plan: "pro", limits: { max_files: 12000 } }; + const a = answers[name]; + if (a === undefined) throw new Error(`Tool ${name} not found`); + return typeof a === "function" ? a(args) : a; + } }; + const realFetch = global.fetch; + global.fetch = async () => ({ ok: true, json: async () => ({ sha: "staged1" }) }); + const saved = {}; + for (const k of ["GITHUB_ACTIONS", "CLAUDE_CODE_SESSION_ID", "CLAUDECODE", "CODEX_SESSION_ID", "CODEX_HOME", "CODEX_SANDBOX", ...Object.keys(env)]) { saved[k] = process.env[k]; delete process.env[k]; } + Object.assign(process.env, env); + const names = () => calls.map(([n]) => n); + try { + const r = await deploy(client, dir, opts, () => {}); + return { r, calls, names: names(), sent: (calls.find(([n]) => n === "deploy") || [])[1] }; + } catch (e) { + e.calls = calls; + e.names = names(); + throw e; + } finally { + global.fetch = realFetch; + for (const [k, v] of Object.entries(saved)) { if (v === undefined) delete process.env[k]; else process.env[k] = v; } + } +} +const published = (sha, extra = {}) => ({ uuid: SPACE, url: "https://spacesheep.dev/@y/q3", sha, is_update: true, ...extra }); +const ME = { CLAUDE_CODE_SESSION_ID: "sess-me" }; +/** list_versions as today's tool answers it: the head pushed by another Claude Code session on mac-2. */ +const byOther = (more = []) => ({ space: { uuid: SPACE, title: "Q3" }, versions: [ + { number: 2, name: "Edit", sha: "live22222222", latest: true, via: "mcp", pushed_by: { label: "Claude Code", machine: "mac-2", session_id: "sess-other" } }, + ...more, +] }); +const filesOf = (entries) => ({ files: entries.map(([p, c]) => ({ path: p, staged_sha: stagedSha(p, Buffer.from(c)) })), version: { id: "live22222222" }, page: {} }); + +test("no base, live version by another session, different files: stops before any upload, naming who and the three ways on", async () => { + const dir = page(); + await assert.rejects(run(dir, { space: SPACE }, { list_versions: byOther(), list_files: filesOf([["index.html", "theirs"]]) }, ME), (e) => { + assert.deepEqual(e.names, ["list_versions", "list_files"], "no stage_begin, no upload, no deploy"); + assert.match(e.message, /^The live version \(live22222222\) was published by another session \(Claude Code on mac-2, session sess-other\)/); + assert.match(e.message, /Pull it first with `spacesheep read 11111111-2222-4333-8444-555555555555 -o ` and merge/); + assert.match(e.message, /--base /); + assert.match(e.message, /--replace/); + assert.equal(e.refusal.code, "conflict"); + assert.equal(refusals.exitCodeFor(e), 1); + assert.match(refusals.errorWords(e), /\n What to do: merge first — spacesheep read 11111111-2222-4333-8444-555555555555 -o /); + return true; + }); + assert.equal(savedBase({ origin: ORIGIN, space: SPACE, dir }), null); +}); + +test("another account's or the browser's version counts as someone else too", async () => { + for (const [row, who] of [ + [{ sha: "live22222222", latest: true, via: "mcp" }, "someone else (another account)"], + [{ sha: "live22222222", latest: true, via: "viewer" }, "Shepherd"], + ]) { + await assert.rejects(run(page(), { space: SPACE }, { list_versions: { versions: [row] }, list_files: filesOf([["index.html", "x"]]) }, ME), + (e) => e.message.includes(`published by ${who},`) && !e.names.includes("deploy")); + } +}); + +test("no base, and the same files are live: nothing is deployed, and the folder builds on that version from now on", async () => { + const dir = page({ uuid: SPACE, slug: "q3", deployed_sha: "old000000000" }); + // The pin's deployed_sha is the base when it has one, so this folder names none: no pin. + fs.rmSync(path.join(dir, ".spacesheep.json")); + const { r, names } = await run(dir, { space: SPACE }, { list_versions: byOther(), list_files: filesOf([["index.html", HTML]]) }, ME); + assert.deepEqual(names, ["list_versions", "list_files"]); + assert.equal(r.unchanged, true); + assert.equal(r.sha, "live22222222"); + assert.equal(savedBase({ origin: ORIGIN, space: SPACE, dir }), "live22222222"); + assert.equal(pinOf(dir).space, SPACE); + // The next deploy (changed files) names it, with no look first. + fs.writeFileSync(path.join(dir, "index.html"), HTML.replace("q3", "q3, again")); + const next = await run(dir, {}, { deploy: published("next33333333") }, ME); + assert.equal(next.sent.base_sha, "live22222222"); + assert.ok(!next.names.includes("list_versions")); +}); + +test("the same files with new metadata go out, built on the live version", async () => { + const { sent } = await run(page(), { space: SPACE, title: "Q3 final" }, { list_versions: byOther(), list_files: filesOf([["index.html", HTML]]), deploy: published("meta44444444") }, ME); + assert.equal(sent.base_sha, "live22222222"); + assert.equal(sent.title, "Q3 final"); +}); + +test("the server's own guess goes on as before: this session wrote the head or an older version, or nothing can be told", async () => { + const mine = { sha: "mine11111111", via: "mcp", pushed_by: { label: "Claude Code", machine: "mac-1", session_id: "sess-me" } }; + for (const versions of [ + { versions: [{ ...mine, latest: true }] }, + byOther([mine]), + // No session to compare on one side: the server decides. + { versions: [{ sha: "live22222222", latest: true, via: "mcp", pushed_by: { label: "Codex", machine: "mac-1" } }] }, + // A live link's placeholder, and a blank starter: nothing to lose. + { versions: [{ sha: "live22222222", latest: true, via: "mcp", name: "Live link started" }] }, + { versions: [{ sha: "live22222222", latest: true, via: "blank" }] }, + // Versions a viewer can't list; a server whose rows don't say who. + "This space's version history is readable only by its owner and editors.", + { versions: [{ id: "live22222222" }] }, + ]) { + const { sent, names } = await run(page(), { space: SPACE }, { list_versions: versions, list_files: filesOf([["index.html", "theirs"]]), deploy: published("go5555555555") }, ME); + assert.equal(sent.base_sha, undefined, JSON.stringify(versions)); + assert.ok(!names.includes("list_files"), "no file listing when the writer can't be told apart"); + } + // The live files can't be listed (an older server): the server decides. + const { sent } = await run(page(), { space: SPACE }, { list_versions: byOther(), deploy: published("go6666666666") }, ME); + assert.equal(sent.base_sha, undefined); +}); + +test("writerOf goes by the session, the server's way", () => { + const me = { session_id: "S" }; + assert.equal(writerOf({ via: "mcp", pushed_by: { session_id: "s" } }, me), "mine"); + assert.equal(writerOf({ via: "automation", pushed_by: { session_id: "t" } }, me), "other"); + assert.equal(writerOf({ via: "edit", pushed_by: { session_id: "s" } }, me), "other"); + assert.equal(writerOf({ via: "mcp" }, me), "other"); + assert.equal(writerOf({ via: "mcp", pushed_by: { machine: "m" } }, me), "unsure"); +}); + +test("a pin's deployed_sha (the /sheep skill's .spacesheep.json) is the base, and is kept current", async () => { + const dir = page({ uuid: SPACE, slug: "q3", org: null, deployed_sha: "5c111111111a", deployed_at: "2026-11-01T00:00:00Z" }); + const one = await run(dir, {}, { deploy: published("c2222222222a") }, ME); + assert.equal(one.sent.uuid, SPACE, "the skill's uuid pins the space"); + assert.equal(one.sent.base_sha, "5c111111111a"); + assert.ok(!one.names.includes("list_versions"), "a base is named: no look first"); + assert.equal(pinOf(dir).deployed_sha, "c2222222222a"); + assert.equal(pinOf(dir).uuid, SPACE); + // The skill publishes again later and writes a newer deployed_sha: that one is the base. + fs.writeFileSync(path.join(dir, ".spacesheep.json"), JSON.stringify({ ...pinOf(dir), deployed_sha: "5c333333333a", deployed_at: "2099-01-01T00:00:00Z" })); + const two = await run(dir, {}, { deploy: published("c4444444444a") }, ME); + assert.equal(two.sent.base_sha, "5c333333333a"); + // Merged: the pin keeps the version the merge was built on, as bases.json does. + const three = await run(dir, {}, { deploy: published("e5555555555a", { merged: { base_sha: "c4444444444a", server_sha: "x", merged: ["index.html"], kept: [] } }) }, ME); + assert.equal(three.sent.base_sha, "c4444444444a"); + assert.equal(pinOf(dir).deployed_sha, "c4444444444a"); + // --space naming another space: the pin's sha is not its base. + const other = await run(dir, { space: "99999999-2222-4333-8444-555555555555" }, { deploy: published("06666666666a") }, ME); + assert.equal(other.sent.base_sha, undefined); +}); + +test("--base latest names the live version just read: the files replace it, said as such", async () => { + const dir = page({ space: SPACE }); + const { sent, r, names } = await run(dir, { base: "latest" }, { list_versions: byOther(), deploy: published("rep777777777") }, ME); + assert.equal(sent.base_sha, "live22222222"); + assert.equal(r.replaced, "live22222222"); + assert.equal(r.base_latest, true); + assert.ok(!names.includes("list_files")); + await assert.rejects(run(page(), { base: "latest" }, {}), (e) => /^--base latest is for updating a space/.test(e.message)); +}); + +test("refusal words: what to do in one line, stop_retrying as the server wrote it with exit code 4", () => { + assert.deepEqual(refusals.refusalOf({ error: "conflict", message: "m" }), { code: "conflict", message: "m" }); + assert.deepEqual(refusals.refusalOf({ code: "invalid", message: "m", violations: [] }), { code: "invalid", message: "m" }); + assert.equal(refusals.refusalOf({ error: "Space not found." }), null); + const perm = refusals.refusalOf(`You can't change this space: only its owner, @ana, and people it was shared with as editors can. Ask @ana to share it with you with "Can edit". Nothing was changed.`); + assert.equal(perm.permission, true); + assert.match(refusals.nextStep(perm), /share it with you with "Can edit", or publish your own copy with --new/); + for (const code of refusals.NO_RETRY) assert.ok(refusals.nextStep({ code }), code); + const stop = Object.assign(new Error("x"), { refusal: { code: "stop_retrying", message: "Refused 5 times in 10 minutes: stop." } }); + assert.equal(refusals.exitCodeFor(stop), 4); + assert.match(refusals.errorWords(stop), /^Refused 5 times in 10 minutes: stop\.\n What to do: stop/); + assert.equal(refusals.exitCodeFor(new Error("x")), 1); +}); + +test("the client never sends a refusal again; rate_limited once, after its retry_after", async () => { + const answers = []; + const c = new McpClient("http://x", "k"); + const waits = []; + c.sleep = async (ms) => { waits.push(ms); }; + let n = 0; + c.callRaw = async () => { n++; return answers.shift(); }; + const text = (o, isError) => ({ isError, content: [{ type: "text", text: JSON.stringify(o) }] }); + + for (const code of ["conflict", "error", "forbidden", "invalid", "would_drop_files", "index_shrunk", "placeholder_page", "stop_retrying"]) { + n = 0; + answers.push(text({ error: code, message: `no (${code})` }, true)); + await assert.rejects(c.call("deploy", {}), (e) => e.refusal.code === code && e.message === `${code}: no (${code})`); + assert.equal(n, 1, code); + // The same word as an answer (deploy's refusals aren't isError): handed back, not retried. + n = 0; + answers.push(text({ error: code, message: "no" }, false)); + assert.equal((await c.call("deploy", {})).error, code); + assert.equal(n, 1); + } + n = 0; + answers.push(text({ error: "rate_limited", message: "slow down", retry_after: 3 }, true), text({ error: "rate_limited", message: "slow down", retry_after: 3 }, true)); + await assert.rejects(c.call("deploy", {}), (e) => e.refusal.code === "rate_limited"); + assert.equal(n, 2, "one retry, then the refusal"); + assert.deepEqual(waits, [3000]); + n = 0; + answers.push(text({ error: "rate_limited", message: "tomorrow", retry_after: 3600 }, true)); + await assert.rejects(c.call("deploy", {}), (e) => e.refusal.retry_after === 3600); + assert.equal(n, 1, "a long wait is not waited out"); + answers.push(text({ error: "rate_limited", retry_after: 1 }, false), text({ uuid: "u", url: "x" }, false)); + assert.equal((await c.call("deploy", {})).uuid, "u"); +}); + +// ---------------------------------------------------------------- end to end, through bin/spacesheep.js + +function server(answer) { + const deploys = []; + const s = http.createServer((req, res) => { + let body = ""; + req.on("data", (d) => { body += d; }); + req.on("end", () => { + const send = (status, o) => { res.writeHead(status, { "Content-Type": "application/json" }); res.end(o === undefined ? "" : JSON.stringify(o)); }; + if (req.method === "PUT") return send(200, { sha: "abcabcabcabc" }); + if (req.url === "/v1/doors.json") return send(404, { code: "not_found", message: "none" }); + if (req.url !== "/mcp") return send(404, { code: "not_found", message: "no route" }); + const m = JSON.parse(body); + if (m.method === "notifications/initialized") return send(202); + if (m.method === "initialize") return send(200, { jsonrpc: "2.0", id: m.id, result: { protocolVersion: "2025-06-18", capabilities: {}, serverInfo: { name: "t", version: "0" } } }); + const { name } = m.params; + if (name === "stage_begin") return send(200, { jsonrpc: "2.0", id: m.id, result: { content: [{ type: "text", text: JSON.stringify({ upload_url: `http://127.0.0.1:${s.address().port}/up`, plan: "pro", limits: { max_files: 12000 } }) }] } }); + if (name === "deploy") deploys.push(m.params.arguments); + return send(200, { jsonrpc: "2.0", id: m.id, result: answer(name) }); + }); + }); + return new Promise((r) => s.listen(0, "127.0.0.1", () => r({ s, deploys, origin: `http://127.0.0.1:${s.address().port}` }))); +} +function cli(args, env, cwd) { + return new Promise((resolve) => { + const p = spawn(process.execPath, [path.join(__dirname, "..", "bin", "spacesheep.js"), ...args], { cwd, env: { PATH: process.env.PATH, SPACESHEEP_QUIET: "1", ...env } }); + let out = "", err = ""; + p.stdout.on("data", (d) => { out += d; }); + p.stderr.on("data", (d) => { err += d; }); + p.on("close", (code) => resolve({ code, out, err })); + }); +} + +test("end to end: stop_retrying prints the server's message as it is and exits 4; a permission refusal exits 1 with what to do; neither is sent twice", async () => { + let answer; + const { s, deploys, origin } = await server(() => answer); + const env = { SPACESHEEP_ORIGIN: origin, SPACESHEEP_KEY: "ss_test", SPACESHEEP_CONFIG_DIR: tmp(), HOME: tmp() }; + try { + const said = "This deploy was refused 5 times in 10 minutes with the same answer, so the server stops taking it. Nothing was deployed."; + answer = { content: [{ type: "text", text: JSON.stringify({ error: "stop_retrying", message: said }) }] }; + const dir = page(); + const stop = await cli(["deploy", dir], env, dir); + assert.equal(stop.code, 4, stop.err); + assert.ok(stop.err.includes(`✗ ${said}\n What to do: stop`), stop.err); + assert.equal(deploys.length, 1); + + answer = { isError: true, content: [{ type: "text", text: `You can't change this space: only its owner, @ana, and people it was shared with as editors can. Ask @ana to share it with you with "Can edit". Nothing was changed.` }] }; + const perm = await cli(["deploy", page(), "--space", "https://spacesheep.dev/@ana/plan"], env, dir); + assert.equal(perm.code, 1, perm.err); + assert.match(perm.err, /You can't change this space/); + assert.match(perm.err, /What to do: ask the space's owner to share it with you with "Can edit", or publish your own copy with --new/); + assert.equal(deploys.length, 2); + } finally { s.close(); } +});