@seedance3/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/oauth.js ADDED
@@ -0,0 +1,274 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { CLI_NAME } from "./config.js";
4
+ import { CliError } from "./errors.js";
5
+ export const OAUTH_SCOPE = "profile email offline_access";
6
+ // The website publishes its authorization server for the MCP endpoint; the
7
+ // public API shares the same server and the same tokens.
8
+ const RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource/api/mcp";
9
+ const CALLBACK_PATH = "/callback";
10
+ const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
11
+ const REQUEST_TIMEOUT_MS = 30_000;
12
+ async function getJson(url, fetchImpl) {
13
+ const response = await fetchImpl(url, {
14
+ headers: { accept: "application/json" },
15
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
16
+ });
17
+ if (!response.ok) {
18
+ throw new CliError("auth_discovery_failed", `Could not read ${url} (HTTP ${response.status}).`);
19
+ }
20
+ return response.json();
21
+ }
22
+ function asString(value) {
23
+ return typeof value === "string" && value ? value : undefined;
24
+ }
25
+ export async function discoverAuthServer(origin, fetchImpl = fetch) {
26
+ const resource = (await getJson(`${origin}${RESOURCE_METADATA_PATH}`, fetchImpl));
27
+ const issuer = Array.isArray(resource.authorization_servers)
28
+ ? asString(resource.authorization_servers[0])
29
+ : undefined;
30
+ if (!issuer) {
31
+ throw new CliError("auth_discovery_failed", "The website did not name its sign-in server.");
32
+ }
33
+ const raw = (await getJson(`${issuer.replace(/\/+$/, "")}/.well-known/oauth-authorization-server`, fetchImpl));
34
+ const metadata = {
35
+ issuer: asString(raw.issuer) ?? issuer,
36
+ authorization_endpoint: asString(raw.authorization_endpoint),
37
+ token_endpoint: asString(raw.token_endpoint),
38
+ registration_endpoint: asString(raw.registration_endpoint),
39
+ revocation_endpoint: asString(raw.revocation_endpoint),
40
+ };
41
+ if (!metadata.authorization_endpoint || !metadata.token_endpoint) {
42
+ throw new CliError("auth_discovery_failed", "The sign-in server metadata is incomplete.");
43
+ }
44
+ return metadata;
45
+ }
46
+ /**
47
+ * Registers this installation as a public OAuth client (no secret, PKCE),
48
+ * the way MCP clients register.
49
+ */
50
+ export async function registerClient(params) {
51
+ const endpoint = params.metadata.registration_endpoint;
52
+ if (!endpoint) {
53
+ throw new CliError("auth_registration_unavailable", "The sign-in server does not accept new apps.");
54
+ }
55
+ const response = await (params.fetchImpl ?? fetch)(endpoint, {
56
+ method: "POST",
57
+ headers: {
58
+ "content-type": "application/json",
59
+ accept: "application/json",
60
+ },
61
+ body: JSON.stringify({
62
+ client_name: CLI_NAME,
63
+ redirect_uris: [params.redirectUri],
64
+ grant_types: ["authorization_code", "refresh_token"],
65
+ response_types: ["code"],
66
+ token_endpoint_auth_method: "none",
67
+ scope: OAUTH_SCOPE,
68
+ }),
69
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
70
+ });
71
+ const body = (await response.json().catch(() => null));
72
+ const clientId = asString(body?.client_id);
73
+ if (!response.ok || !clientId) {
74
+ throw new CliError("auth_registration_failed", `Could not register the CLI with the sign-in server (HTTP ${response.status}).`);
75
+ }
76
+ return {
77
+ issuer: params.metadata.issuer,
78
+ clientId,
79
+ redirectUri: params.redirectUri,
80
+ };
81
+ }
82
+ export function createPkce() {
83
+ const verifier = randomBytes(32).toString("base64url");
84
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
85
+ return { verifier, challenge };
86
+ }
87
+ export function buildAuthorizationUrl(params) {
88
+ const url = new URL(params.metadata.authorization_endpoint);
89
+ url.search = new URLSearchParams({
90
+ response_type: "code",
91
+ client_id: params.client.clientId,
92
+ redirect_uri: params.client.redirectUri,
93
+ scope: OAUTH_SCOPE,
94
+ state: params.state,
95
+ code_challenge: params.challenge,
96
+ code_challenge_method: "S256",
97
+ }).toString();
98
+ return url.toString();
99
+ }
100
+ const PAGE_STYLE = "font-family:system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 1rem;text-align:center";
101
+ function callbackPage(title, body) {
102
+ return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title></head><body style="${PAGE_STYLE}"><h1>${title}</h1><p>${body}</p></body></html>`;
103
+ }
104
+ /**
105
+ * Listens on 127.0.0.1 for the browser's redirect. Only GET /callback with
106
+ * the expected state is accepted; anything else is ignored, so another page
107
+ * cannot complete the sign-in.
108
+ */
109
+ export function listenForAuthorizationCode(params) {
110
+ return new Promise((resolveListener, rejectListener) => {
111
+ let settle;
112
+ const code = new Promise((resolve, reject) => {
113
+ settle = { resolve, reject };
114
+ });
115
+ // A late rejection (timeout after the caller gave up) is not unhandled.
116
+ code.catch(() => undefined);
117
+ const server = createServer((request, response) => {
118
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
119
+ if (request.method !== "GET" || url.pathname !== CALLBACK_PATH) {
120
+ response.writeHead(404).end();
121
+ return;
122
+ }
123
+ if (url.searchParams.get("state") !== params.state) {
124
+ response.writeHead(400).end();
125
+ return;
126
+ }
127
+ response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
128
+ let authorizationCode;
129
+ try {
130
+ authorizationCode = authorizationCodeFrom(url);
131
+ }
132
+ catch (error) {
133
+ response.end(callbackPage("Sign-in was not completed", "Return to your terminal for details."));
134
+ settle.reject(error);
135
+ close();
136
+ return;
137
+ }
138
+ response.end(callbackPage("Signed in to Seedance 3.0 AI", "You can close this tab and return to your terminal."));
139
+ settle.resolve(authorizationCode);
140
+ close();
141
+ });
142
+ const timer = setTimeout(() => {
143
+ settle.reject(new CliError("auth_timeout", "Timed out waiting for the browser."));
144
+ close();
145
+ }, params.timeoutMs ?? LOGIN_TIMEOUT_MS);
146
+ timer.unref();
147
+ function close() {
148
+ clearTimeout(timer);
149
+ server.close();
150
+ server.closeAllConnections();
151
+ }
152
+ server.once("error", rejectListener);
153
+ server.listen(params.port, "127.0.0.1", () => {
154
+ const address = server.address();
155
+ if (!address || typeof address === "string") {
156
+ close();
157
+ rejectListener(new Error("Could not open a local port."));
158
+ return;
159
+ }
160
+ resolveListener({ port: address.port, code, close });
161
+ });
162
+ });
163
+ }
164
+ /** The code of an authorization response, or the error it reports. */
165
+ function authorizationCodeFrom(url) {
166
+ const error = url.searchParams.get("error");
167
+ const code = url.searchParams.get("code");
168
+ if (!error && code)
169
+ return code;
170
+ throw new CliError(error === "access_denied" ? "auth_denied" : "auth_failed", error === "access_denied"
171
+ ? "Access was denied in the browser."
172
+ : `Sign-in failed: ${error ?? "no authorization code"}.`);
173
+ }
174
+ /**
175
+ * The code from the address a browser ended on after the user allowed
176
+ * access, pasted back by the user when the browser ran on another device.
177
+ * It must be this client's redirect address and carry the expected state.
178
+ */
179
+ export function authorizationCodeFromPastedUrl(pasted, expected) {
180
+ const value = pasted.trim().replace(/^["']|["']$/g, "");
181
+ let url;
182
+ try {
183
+ url = new URL(value);
184
+ }
185
+ catch {
186
+ throw new CliError("auth_failed", "That is not the address from the browser.", `Copy the whole address that starts with ${expected.redirectUri}.`);
187
+ }
188
+ const redirect = new URL(expected.redirectUri);
189
+ if (url.origin !== redirect.origin || url.pathname !== redirect.pathname) {
190
+ throw new CliError("auth_failed", "That address is not the sign-in result.", `Copy the address the browser ends on after you allow access; it starts with ${expected.redirectUri}.`);
191
+ }
192
+ if (url.searchParams.get("state") !== expected.state) {
193
+ throw new CliError("auth_failed", "That address belongs to a different sign-in attempt.", "Use the link from the latest sign-in, or start again.");
194
+ }
195
+ return authorizationCodeFrom(url);
196
+ }
197
+ export function redirectUriFor(port) {
198
+ return `http://127.0.0.1:${port}${CALLBACK_PATH}`;
199
+ }
200
+ export function portOf(redirectUri) {
201
+ return Number(new URL(redirectUri).port);
202
+ }
203
+ async function postForm(endpoint, fields, fetchImpl) {
204
+ const response = await fetchImpl(endpoint, {
205
+ method: "POST",
206
+ headers: {
207
+ "content-type": "application/x-www-form-urlencoded",
208
+ accept: "application/json",
209
+ },
210
+ body: new URLSearchParams(fields).toString(),
211
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
212
+ });
213
+ const body = ((await response.json().catch(() => null)) ??
214
+ {});
215
+ return { response, body };
216
+ }
217
+ export function toCredentials(body, now = Date.now(), previousRefreshToken) {
218
+ const accessToken = asString(body.access_token);
219
+ if (!accessToken) {
220
+ throw new CliError("auth_failed", "The sign-in server returned no access token.");
221
+ }
222
+ const expiresIn = Number(body.expires_in);
223
+ return {
224
+ accessToken,
225
+ // A refresh response may omit the refresh token; the old one stays valid.
226
+ refreshToken: asString(body.refresh_token) ?? previousRefreshToken,
227
+ expiresAt: Number.isFinite(expiresIn) && expiresIn > 0
228
+ ? now + expiresIn * 1000
229
+ : undefined,
230
+ };
231
+ }
232
+ function tokenError(body, status) {
233
+ const code = asString(body.error) ?? `http_${status}`;
234
+ const description = asString(body.error_description);
235
+ return new CliError("auth_failed", `Sign-in failed (${code}${description ? `: ${description}` : ""}).`);
236
+ }
237
+ export async function exchangeAuthorizationCode(params) {
238
+ const { response, body } = await postForm(params.metadata.token_endpoint, {
239
+ grant_type: "authorization_code",
240
+ code: params.code,
241
+ redirect_uri: params.client.redirectUri,
242
+ client_id: params.client.clientId,
243
+ code_verifier: params.verifier,
244
+ }, params.fetchImpl ?? fetch);
245
+ if (!response.ok)
246
+ throw tokenError(body, response.status);
247
+ return toCredentials(body);
248
+ }
249
+ /** Exchanges the refresh token; null when the grant is gone (sign in again). */
250
+ export async function refreshCredentials(params) {
251
+ const refreshToken = params.credentials.refreshToken;
252
+ if (!refreshToken)
253
+ return null;
254
+ const { response, body } = await postForm(params.tokenEndpoint, {
255
+ grant_type: "refresh_token",
256
+ refresh_token: refreshToken,
257
+ client_id: params.clientId,
258
+ }, params.fetchImpl ?? fetch);
259
+ if (response.status === 400 || response.status === 401)
260
+ return null;
261
+ if (!response.ok)
262
+ throw tokenError(body, response.status);
263
+ return toCredentials(body, Date.now(), refreshToken);
264
+ }
265
+ /** Best effort: true when the server confirmed the revocation. */
266
+ export async function revokeToken(params) {
267
+ try {
268
+ const { response } = await postForm(params.revocationEndpoint, { token: params.token, client_id: params.clientId }, params.fetchImpl ?? fetch);
269
+ return response.ok;
270
+ }
271
+ catch {
272
+ return false;
273
+ }
274
+ }
@@ -0,0 +1,138 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+ import { PACKAGE_NAME } from "./config.js";
5
+ import { CliError } from "./errors.js";
6
+ /**
7
+ * Models the CLI generates with: those the public API can quote, the same
8
+ * set the MCP server offers. Quote first, then generate, is the CLI's flow.
9
+ */
10
+ export const SUPPORTED_MODELS = [
11
+ "seedance25",
12
+ "seedance2",
13
+ "kling4",
14
+ "video-upscale",
15
+ "gpt-image-2.5",
16
+ "gpt-image-2",
17
+ "nano-banana-pro",
18
+ "nano-banana-2",
19
+ "nano-banana-2-lite",
20
+ "seedream-5-pro",
21
+ "seedream-5-lite",
22
+ "image-upscale",
23
+ ];
24
+ export function isSupportedModel(model) {
25
+ return SUPPORTED_MODELS.includes(model);
26
+ }
27
+ export async function readRequestFile(file) {
28
+ let text;
29
+ try {
30
+ text = await readFile(file, "utf8");
31
+ }
32
+ catch {
33
+ throw new CliError("file_not_found", `Request file not found: ${file}`);
34
+ }
35
+ let parsed;
36
+ try {
37
+ parsed = JSON.parse(text);
38
+ }
39
+ catch {
40
+ throw new CliError("invalid_request", `${file} is not valid JSON.`);
41
+ }
42
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
43
+ throw new CliError("invalid_request", `${file} must hold a JSON object.`);
44
+ }
45
+ const { model, ...body } = parsed;
46
+ if (typeof model !== "string" || !isSupportedModel(model)) {
47
+ throw new CliError("invalid_request", typeof model === "string"
48
+ ? `Model "${model}" is not available in the CLI.`
49
+ : 'The request needs a "model" field.', `Use one of: ${SUPPORTED_MODELS.join(", ")}. See \`seedance3 models\`. A model added since this version needs the latest CLI: npm install -g ${PACKAGE_NAME}`);
50
+ }
51
+ return { model, body, baseDir: path.dirname(path.resolve(file)) };
52
+ }
53
+ /**
54
+ * Resolves a file path the way a shell would for `~` and `~/…`, which users
55
+ * and agents often write in a request file, against `baseDir` otherwise.
56
+ */
57
+ export function resolveLocalPath(value, baseDir) {
58
+ if (value === "~")
59
+ return homedir();
60
+ if (value.startsWith("~/"))
61
+ return path.join(homedir(), value.slice(2));
62
+ return path.resolve(baseDir, value);
63
+ }
64
+ const URL_FIELD = /_urls?$/;
65
+ const REMOTE_VALUE = /^(https?|asset):\/\//i;
66
+ /**
67
+ * Local paths in the request's URL fields (`image_url`, `media_urls`, …),
68
+ * including those inside nested objects such as Kling 4.0 subjects
69
+ * (`elements[].image_urls`) and voices (`voices[].audio_url`). Anything that
70
+ * is not an http(s) or asset URL is taken as a file path.
71
+ */
72
+ export function findLocalFiles(request) {
73
+ const refs = [];
74
+ const walk = (value, at, inUrlField) => {
75
+ if (typeof value === "string") {
76
+ if (inUrlField && value.trim() && !REMOTE_VALUE.test(value)) {
77
+ refs.push({ at, path: resolveLocalPath(value, request.baseDir) });
78
+ }
79
+ }
80
+ else if (Array.isArray(value)) {
81
+ value.forEach((item, index) => walk(item, [...at, index], inUrlField));
82
+ }
83
+ else if (value && typeof value === "object") {
84
+ for (const [key, item] of Object.entries(value)) {
85
+ walk(item, [...at, key], URL_FIELD.test(key));
86
+ }
87
+ }
88
+ };
89
+ walk(request.body, [], false);
90
+ return refs;
91
+ }
92
+ /** A copy of `target` with the value at `at` replaced; `target` is untouched. */
93
+ function withValueAt(target, at, value) {
94
+ const [key, ...rest] = at;
95
+ if (key === undefined)
96
+ return value;
97
+ if (Array.isArray(target)) {
98
+ const copy = [...target];
99
+ copy[key] = withValueAt(target[key], rest, value);
100
+ return copy;
101
+ }
102
+ const record = target;
103
+ return { ...record, [key]: withValueAt(record[key], rest, value) };
104
+ }
105
+ /** The body with each local path replaced by its uploaded URL. */
106
+ export function withUploadedUrls(body, refs, urls) {
107
+ return refs.reduce((next, ref, position) => withValueAt(next, ref.at, urls[position]), body);
108
+ }
109
+ // The website names the default Seedance 2.0 tier "Fast"; the public API
110
+ // calls it "standard". The CLI uses the website's names, exactly as the MCP
111
+ // server does (lib/mcp/seedance-tiers.ts on the website).
112
+ const SEEDANCE_2_MODELS = new Set(["seedance", "seedance2"]);
113
+ export function toApiTier(model, body) {
114
+ if (model !== "seedance2")
115
+ return body;
116
+ // The API's own name is refused, as the MCP server refuses it, so users
117
+ // only ever meet the website's names.
118
+ if (body.quality_tier === "standard") {
119
+ throw new CliError("invalid_request", 'quality_tier "standard" is not a Seedance 2.0 tier.', 'Use "mini", "fast" or "pro".');
120
+ }
121
+ if (body.quality_tier !== "fast")
122
+ return body;
123
+ return { ...body, quality_tier: "standard" };
124
+ }
125
+ /** A quote, submission or task with the Seedance 2.0 tier named as on the website. */
126
+ export function fromApiTier(record) {
127
+ if (!record || typeof record !== "object")
128
+ return record;
129
+ const { model, quality_tier: tier } = record;
130
+ if (typeof model !== "string" || !SEEDANCE_2_MODELS.has(model))
131
+ return record;
132
+ if (tier !== "standard")
133
+ return record;
134
+ return { ...record, quality_tier: "fast" };
135
+ }
136
+ export function fromApiTierMessage(message) {
137
+ return message.replace(/\bstandard tier\b/g, "fast tier");
138
+ }
package/dist/schema.js ADDED
@@ -0,0 +1,79 @@
1
+ import { CliError } from "./errors.js";
2
+ function isObject(value) {
3
+ return !!value && typeof value === "object" && !Array.isArray(value);
4
+ }
5
+ /** Inlines `#/components/...` references so the schema reads on its own. */
6
+ function resolveRefs(value, root, depth = 0) {
7
+ if (depth > 20)
8
+ return value;
9
+ if (Array.isArray(value))
10
+ return value.map((item) => resolveRefs(item, root, depth + 1));
11
+ if (!isObject(value))
12
+ return value;
13
+ const ref = value.$ref;
14
+ if (typeof ref === "string" && ref.startsWith("#/")) {
15
+ const target = ref
16
+ .slice(2)
17
+ .split("/")
18
+ .reduce((node, key) => (isObject(node) ? node[key] : undefined), root);
19
+ return resolveRefs(target, root, depth + 1);
20
+ }
21
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [
22
+ key,
23
+ resolveRefs(item, root, depth + 1),
24
+ ]));
25
+ }
26
+ /** Seedance 2.0's tier is "fast" in the CLI, as on the website. */
27
+ function withWebsiteTierNames(model, schema) {
28
+ if (model !== "seedance2" || !isObject(schema))
29
+ return schema;
30
+ const properties = schema.properties;
31
+ if (!isObject(properties) || !isObject(properties.quality_tier))
32
+ return schema;
33
+ const tier = properties.quality_tier;
34
+ const rename = (item) => (item === "standard" ? "fast" : item);
35
+ return {
36
+ ...schema,
37
+ properties: {
38
+ ...properties,
39
+ quality_tier: {
40
+ ...tier,
41
+ ...(Array.isArray(tier.enum) ? { enum: tier.enum.map(rename) } : {}),
42
+ ...(tier.default !== undefined
43
+ ? { default: rename(tier.default) }
44
+ : {}),
45
+ },
46
+ },
47
+ };
48
+ }
49
+ /**
50
+ * The request fields of one model, from the website's OpenAPI description
51
+ * (/openapi.json), which documents every public API request body.
52
+ */
53
+ export async function describeModel(params) {
54
+ const response = await (params.fetchImpl ?? fetch)(`${params.origin}/openapi.json`, {
55
+ headers: { accept: "application/json" },
56
+ signal: AbortSignal.timeout(30_000),
57
+ });
58
+ if (!response.ok) {
59
+ throw new CliError("schema_unavailable", `Could not read the API description (HTTP ${response.status}).`);
60
+ }
61
+ const spec = (await response.json());
62
+ const paths = isObject(spec.paths) ? spec.paths : {};
63
+ const operation = paths[params.model.endpoint]
64
+ ?.post;
65
+ const schema = isObject(operation)
66
+ ? operation.requestBody?.content
67
+ : undefined;
68
+ const json = isObject(schema)
69
+ ? schema["application/json"]?.schema
70
+ : undefined;
71
+ return {
72
+ id: params.model.id,
73
+ name: params.model.name,
74
+ type: params.model.type,
75
+ modes: params.model.modes,
76
+ request_schema: withWebsiteTierNames(params.model.id, resolveRefs(json, spec)) ?? null,
77
+ note: 'Write the request as JSON with "model" plus these fields. URL fields also accept paths to files on this computer.',
78
+ };
79
+ }