diff --git a/lib/doors.js b/lib/doors.js index 1ead1fc..28c6279 100644 --- a/lib/doors.js +++ b/lib/doors.js @@ -234,7 +234,7 @@ async function parseInputs(found, argv, { env = process.env, readStdin, given = const [flagName, inline] = a.includes("=") ? pair(a) : [a, undefined]; let spec; if (!via) { - const f = byFlag.get(flagName); + const f = byFlag.get(flagName) || byFlag.get((FLAG_ALIASES[cli.command] || {})[flagName]); if (!f) throw new UsageError(`${cli.command} takes no ${flagName}`, usage); spec = specOf(f.input, flagName); } else { @@ -349,7 +349,17 @@ function canRun(table, argv) { const found = match(table, argv); return !!found && (!(argv.includes("-o") || argv.includes("--out")) || [].concat(found).some((f) => writes(f.method))); } -const writes = (method) => !!(method.answer_folder || method.answer_bytes); +const writes = (method) => !!(method.answer_folder || method.answer_bytes || linkAt(method)); +/** Where an answer's file link is, from the call's own answer schema: a `download_url` at its top (`[]`) or in its + * one item (`["image"]`), else null. `-o` fetches that link (with no key: the link is the credential). */ +function linkAt(method) { + const props = (method.mcp && method.mcp.outputSchema && method.mcp.outputSchema.properties) || {}; + if (props.download_url) return []; + const item = Object.keys(props).find((k) => props[k] && props[k].properties && props[k].properties.download_url); + return item ? [item] : null; +} +/** Flags a command also takes under the name people use (`images generate --aspect 16:9`). */ +const FLAG_ALIASES = { "spacesheep images generate": { "--aspect": "--aspect-ratio" } }; /** Several old-name matches (a `when` each): the one whose `when` the line meets, else the * one without. A form its `when` picked answers for the line: its refusal is the line's, * never another form's call. */ @@ -471,6 +481,24 @@ function takeBytes(method, answer, outFile, writeFile) { return shown; } +/** The file an answer links to (linkAt): fetched and written to -o, the link shown as what was written. Only an + * https link, or http on this machine (a local server); a refusal is the call's error, never a file. */ +async function takeLink(method, answer, outFile, { fetchImpl = fetch, writeFile = fs.writeFileSync } = {}) { + const at = linkAt(method); + if (!at || !outFile) return null; + const holder = at.length ? answer && answer[at[0]] : answer; + const url = holder && holder.download_url; + let u; + try { u = new URL(url); } catch { throw new Error("the answer has no link to download"); } + if (!(u.protocol === "https:" || (u.protocol === "http:" && /^(localhost|127\.0\.0\.1)$/.test(u.hostname)))) throw new Error(`refused to download ${u.protocol}//${u.host}: not https`); + const res = await fetchImpl(u.href, { redirect: "error" }); + if (!res.ok) throw new Error(`the download answered HTTP ${res.status}`); + const bytes = Buffer.from(await res.arrayBuffer()); + writeFile(outFile, bytes); + const done = { ...holder, download_url: `${bytes.length} bytes → ${outFile}` }; + return at.length ? { ...answer, [at[0]]: done } : done; +} + /** A folder of files (`answer_folder` names the call's own fields): `-o FOLDER` writes every file the answer lists, * `-o FILE` with the path input that one file, each file's parts joined. The first answer's served version goes on * every later call, so the folder is one version. A folder is written only when new or empty, and only inside it. */ @@ -556,6 +584,8 @@ function helpFor(found, meanings) { } lines.push(` ${"--json".padEnd(26)} print the server's answer as it came`); if (method.answer_bytes) lines.push(` ${"-o, --out ".padEnd(26)} write the answer's bytes to a file`); + if (linkAt(method)) lines.push(` ${"-o, --out ".padEnd(26)} download the file it links to`); + for (const [alias, flag] of Object.entries(FLAG_ALIASES[cli.command] || {})) lines.push(` ${alias.padEnd(26)} the same as ${flag}`); if (method.answer_folder) lines.push(` ${"-o, --out ".padEnd(26)} write every file to a new or empty folder (with --${method.answer_folder.path.replace(/_/g, "-")}, that file to )`); const words = wordsOf(method.errors); if (words.length) lines.push("\n can refuse", ...refusalLines(words, meanings)); @@ -600,6 +630,9 @@ async function run(found, argv, ctx) { if (parsed.help) { out(helpFor(chosen, ctx.meanings).replace(/\n$/, "")); return 0; } const { method } = chosen; if (parsed.global.out && !writes(method)) { err("\n ✗ -o has nothing to write for this call on this server: its answer is neither a file nor a folder\n"); return 2; } + // A download is asked for: refused before the call (it may cost the person), never silently skipped after it. + const fetchesLink = !!(parsed.global.out && linkAt(method) && !method.answer_bytes); + if (fetchesLink && parsed.global.json) { err("\n ✗ -o downloads the file and --json prints the answer as it came: use one of them\n"); return 2; } const key = ctx.key(); if (!key) { err("\n ✗ not signed in — run `spacesheep login` (or set SPACESHEEP_KEY)\n"); return 3; } if (method.answer_folder && parsed.global.out) { @@ -632,10 +665,15 @@ async function run(found, argv, ctx) { return stop ? ref.EXIT_STOP_RETRYING : 1; } if (parsed.global.json) { if (text) out(text.replace(/\n$/, "")); return 0; } + if (!text && fetchesLink) { err("\n ✗ the answer was empty, so there was nothing to download\n"); return 1; } if (!text) return 0; let answer; - try { answer = JSON.parse(text); } catch { out(text.replace(/\n$/, "")); return 0; } - const shown = takeBytes(method, answer, parsed.global.out, ctx.writeFile || fs.writeFileSync) || answer; + try { answer = JSON.parse(text); } catch { out(text.replace(/\n$/, "")); if (fetchesLink) { err("\n ✗ the answer wasn't JSON, so there was nothing to download\n"); return 1; } return 0; } + let shown = takeBytes(method, answer, parsed.global.out, ctx.writeFile || fs.writeFileSync); + if (!shown) { + try { shown = (await takeLink(method, answer, parsed.global.out, { fetchImpl, writeFile: ctx.writeFile })) || answer; } + catch (e) { err(`\n ✗ ${e.message}\n`); return 1; } + } // Today's command on a new call keeps today's text: its own lines, and none at all for nothing. if (ctx.lines) { const own = ctx.lines(shown); if (own.length) out(own.join("\n")); return 0; } const lines = plain(shown); @@ -647,5 +685,5 @@ async function run(found, argv, ctx) { module.exports = { MISSING_TTL, FETCH_TIMEOUT, PROBE_TIMEOUT, NEED_TIMEOUT, REVALIDATE_TIMEOUT, UsageError, cachePath, loadTable, match, canRun, namesWord, verbsOf, parseInputs, resolve, - pathValue, buildRequest, errorInfo, refusalWords, plain, takeBytes, takeFolder, helpFor, nounHelp, tableHelp, run, call, + pathValue, buildRequest, errorInfo, refusalWords, plain, takeBytes, takeLink, takeFolder, helpFor, nounHelp, tableHelp, run, call, }; diff --git a/test/doors.test.js b/test/doors.test.js index 7aa1d54..3c35de9 100644 --- a/test/doors.test.js +++ b/test/doors.test.js @@ -255,6 +255,42 @@ test("bytes in an answer go to -o, never the terminal", () => { assert.equal(shown.png, "7 bytes → /x/shot.png"); }); +test("images generate: --aspect is --aspect-ratio, and -o downloads the file the answer links to, with no key", async () => { + const r = await request("images generate --prompt sheep --aspect 4:3"); + assert.equal(r.url, `${ORIGIN}/v1/me/images:generate`); + assert.deepEqual(JSON.parse(r.body), { prompt: "sheep", aspect_ratio: "4:3" }); + const asked = [], said = [], errs = [], written = []; + const answer = { image: { staged_sha: "0123456789ab", path: "images/a.jpg", download_url: "https://mcp.example/image/tok" } }; + const fetchImpl = async (url, init = {}) => { + asked.push([url, init.headers && init.headers.Authorization]); + return url.endsWith("/image/tok") ? new Response(Buffer.from("JPEGDATA")) : new Response(JSON.stringify(answer)); + }; + const argv = ["images", "generate", "--prompt", "sheep", "-o", "/x/hero.jpg"]; + const found = doors.match(TABLE, argv); + assert.ok(doors.canRun(TABLE, argv)); + const ctx = { origin: ORIGIN, key: () => "ss_test", version: "0", fetchImpl, out: (s) => said.push(s), err: (s) => errs.push(s), writeFile: (f, b) => written.push([f, b.toString()]) }; + assert.equal(await doors.run(found, argv.slice(found.used), ctx), 0); + assert.deepEqual(written, [["/x/hero.jpg", "JPEGDATA"]]); + assert.deepEqual(asked[1], ["https://mcp.example/image/tok", undefined]); + assert.match(said.join("\n"), /staged_sha: 0123456789ab[\s\S]*download_url: 8 bytes → \/x\/hero\.jpg/); + // A link that isn't https is never fetched. + answer.image.download_url = "http://evil.example/x"; + asked.length = 0; + assert.equal(await doors.run(found, argv.slice(found.used), ctx), 1); + assert.equal(asked.length, 1); + assert.match(errs.join(""), /not https/); + // -o with --json is refused before anything is sent; an empty or broken answer is a failure, not a quiet 0. + asked.length = 0; + assert.equal(await doors.run(found, [...argv.slice(found.used), "--json"], ctx), 2); + assert.equal(asked.length, 0); + for (const body of ["", "not json", "null", "{}"]) { + const broken = { ...ctx, fetchImpl: async () => new Response(body) }; + assert.equal(await doors.run(found, argv.slice(found.used), broken), 1); + } + assert.deepEqual(written, [["/x/hero.jpg", "JPEGDATA"]]); + assert.match(doors.helpFor(found), /-o, --out \s+download the file it links to[\s\S]*--aspect\s+the same as --aspect-ratio/); +}); + test("the table: cached per origin, revalidated by ETag, a 404 remembered for a while", async () => { const dir = tmp(); const calls = []; diff --git a/test/fixtures/doors.json b/test/fixtures/doors.json index 97d795b..b37c7e5 100644 --- a/test/fixtures/doors.json +++ b/test/fixtures/doors.json @@ -5186,6 +5186,185 @@ "response": "GetFileResponse" } ] + }, + { + "service": "CaptureService", + "methods": [ + { + "method": "GenerateImage", + "service": "CaptureService", + "doc": "Draw an original picture from words, on your own or your group's Gemini key, staged to publish by its sha.", + "verb": "Generate", + "noun": "Image", + "http": "POST", + "path": "/v1/me/images:generate", + "where": "body", + "callers": [ + "person", + "key", + "connector", + "box" + ], + "machine_tokens": [], + "mcp": { + "name": "generate_image", + "title": "Generate an image", + "annotations": { + "readOnlyHint": false, + "destructiveHint": false, + "idempotentHint": false, + "openWorldHint": true + }, + "refused": [ + "agent" + ], + "description_chars": 106, + "inputSchema": { + "type": "object", + "properties": { + "prompt": { + "type": "string", + "description": "What to draw: subject, composition, style and mood, in one rich sentence. The model doesn't see your page. (text; at most 2,000 characters)" + }, + "aspect_ratio": { + "type": "string", + "description": "Its shape: 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3 or 21:9; 16:9 when left out. (text)" + }, + "path": { + "type": "string", + "description": "Its path inside the space, img/hero.jpg; images/.jpg when left out. (text; at most 512 characters)" + } + }, + "additionalProperties": false, + "required": [ + "prompt" + ] + }, + "outputSchema": { + "type": "object", + "properties": { + "image": { + "type": "object", + "properties": { + "staged_sha": { + "type": "string" + }, + "path": { + "type": "string" + }, + "media_type": { + "type": "string" + }, + "bytes": { + "type": "string", + "pattern": "^-?[0-9]+$" + }, + "width": { + "type": "integer" + }, + "height": { + "type": "integer" + }, + "download_url": { + "type": "string" + }, + "expires_at": { + "type": "string", + "format": "date-time" + } + } + } + } + } + }, + "cli": { + "command": "spacesheep images generate", + "usage": "spacesheep images generate --prompt [flags]", + "replaces": [], + "args": [], + "flags": [ + { + "flag": "--prompt", + "input": "prompt", + "type": "text", + "required": true, + "doc": "What to draw: subject, composition, style and mood, in one rich sentence. The model doesn't see your page.", + "limits": [ + "at most 2,000 characters" + ] + }, + { + "flag": "--aspect-ratio", + "input": "aspect_ratio", + "type": "text", + "required": false, + "doc": "Its shape: 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3 or 21:9; 16:9 when left out." + }, + { + "flag": "--path", + "input": "path", + "type": "text", + "required": false, + "doc": "Its path inside the space, img/hero.jpg; images/.jpg when left out.", + "limits": [ + "at most 512 characters" + ] + } + ] + }, + "account": false, + "read_key": false, + "errors": [ + "failed_precondition", + "forbidden", + "invalid", + "rate_limited", + "read_only_grant", + "unavailable" + ], + "replaces": [], + "renamed": [], + "answer_bytes": null, + "mask": null, + "inputs": [ + { + "name": "prompt", + "type": "text", + "required": true, + "doc": "What to draw: subject, composition, style and mood, in one rich sentence. The model doesn't see your page.", + "limits": [ + "at most 2,000 characters" + ], + "at": [ + "prompt" + ] + }, + { + "name": "aspect_ratio", + "type": "text", + "required": false, + "doc": "Its shape: 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3 or 21:9; 16:9 when left out.", + "limits": [], + "at": [ + "aspect_ratio" + ] + }, + { + "name": "path", + "type": "text", + "required": false, + "doc": "Its path inside the space, img/hero.jpg; images/.jpg when left out.", + "limits": [ + "at most 512 characters" + ], + "at": [ + "path" + ] + } + ], + "response": "GenerateImageResponse" + } + ] } ], "forwards": {}