@5y/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/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # @5y/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 给 AI 工具(Codex / Claude Code / WorkBuddy)用的 5y 命令行:生图、生视频、素材与任务管理。
4
+
5
+ ## For AI agents (read this first)
6
+
7
+ You can call 5y without any background knowledge:
8
+
9
+ 1. **You cannot create an API key yourself.** Ask your human to open
10
+ <https://5y.com.cn/settings/api-keys>, create a key, and paste it to you.
11
+ 2. Then: `5y login --key <KEY>` → `5y models` → `5y image|video ...`.
12
+ 3. Run `5y` with no arguments for a quick start, examples, and the full command list.
13
+
14
+ Contract you can rely on:
15
+
16
+ - **stdout is exactly one line of JSON**; progress goes to stderr
17
+ - success `{"ok":true,...}` / failure `{"ok":false,"error":{"code","message","retryable","request_id"}}`
18
+ - exit codes: `0` ok · `2` usage · `3` auth · `4` business failure · `5` network/upstream
19
+ - **do not retry when `error.retryable === false`** (content rejection, invalid params)
20
+ - never invent `asset_id` / `job_id` — they only come from this CLI's output
21
+ - omitting `--model` is fine: the server picks a default and echoes it in the response
22
+
23
+ ## 安装
24
+
25
+ ```bash
26
+ npm i -g @5y/cli # 或者直接 npx @5y/cli ...
27
+ ```
28
+
29
+ 需要 Node ≥ 18。
30
+
31
+ ## 开始
32
+
33
+ ```bash
34
+ 5y login --key 5y_xxxxxxxx # Key 在 5y 网页端「个人中心 → API Key」生成
35
+ 5y whoami # 确认身份、工作区与限流
36
+ 5y models --type video # 看可用模型(含默认标记)
37
+ ```
38
+
39
+ ## 生成
40
+
41
+ ```bash
42
+ # 文生图(不传 --model 用服务端默认,输出会回显实际模型与费用)
43
+ 5y image --prompt "一只橘猫,电影感" --out ./out
44
+
45
+ # 视频编辑:把视频里的人脸换成参考图
46
+ 5y upload ./face.png # → asset_id
47
+ 5y video --prompt "把视频里的脸换成参考图的脸" \
48
+ --asset source_video=<视频 asset_id> --asset image=<图 asset_id> \
49
+ --param mode=video_edit --param ratio=adaptive --param duration=-1 \
50
+ --out ./out
51
+ ```
52
+
53
+ ## 等待方式
54
+
55
+ - 默认 `--wait`:等到出片再返回,产物落到 `--out`(默认 `./5y-output`)
56
+ - `--no-wait`:立刻返回 `job_id`,之后用 `5y job get <id>` 查
57
+ - `--callback http://127.0.0.1:PORT/hook`:完成后由 **本机 CLI 进程**投递(带 `X-5y-Signature`),5y 服务端不会连你的本机
58
+
59
+ ## 输出约定
60
+
61
+ - stdout **只有一行 JSON**:`{"ok":true,...}` / `{"ok":false,"error":{...}}`
62
+ - 进度与日志在 stderr
63
+ - 退出码:`0` 成功 · `2` 参数错 · `3` 认证/权限 · `4` 业务失败 · `5` 网络或上游不可用
64
+
65
+ ## 配置
66
+
67
+ `~/.config/5y/config.toml`(600)。也可用环境变量 `5Y_API_KEY`、`5Y_BASE_URL` 覆盖(CI 场景)。
package/bin/5y.mjs ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { run } from '../lib/commands.mjs';
3
+
4
+ run(process.argv.slice(2))
5
+ .then((code) => {
6
+ process.exitCode = code;
7
+ })
8
+ .catch((err) => {
9
+ // run() handles its own errors; this is only a last-resort guard.
10
+ process.stderr.write(`[5y] fatal: ${err && err.message ? err.message : String(err)}\n`);
11
+ process.exitCode = 5;
12
+ });
package/lib/args.mjs ADDED
@@ -0,0 +1,97 @@
1
+ import { UsageError } from './output.mjs';
2
+
3
+ const VALUE_FLAGS = new Set([
4
+ 'key',
5
+ 'base-url',
6
+ 'name',
7
+ 'type',
8
+ 'limit',
9
+ 'cursor',
10
+ 'model',
11
+ 'prompt',
12
+ 'out',
13
+ 'interval',
14
+ 'callback',
15
+ 'timeout',
16
+ 'idempotency-key',
17
+ ]);
18
+
19
+ const MULTI_FLAGS = new Set(['asset', 'param']);
20
+
21
+ const BOOLEAN_FLAGS = new Set(['wait', 'help', 'version']);
22
+
23
+ export const KNOWN_FLAGS = new Set([...VALUE_FLAGS, ...MULTI_FLAGS, ...BOOLEAN_FLAGS, 'no-wait']);
24
+
25
+ /**
26
+ * Minimal long-option parser.
27
+ * Supports: `--flag value`, `--flag=value`, repeated `--asset` / `--param`.
28
+ */
29
+ export function parseArgs(argv) {
30
+ const flags = {};
31
+ const multi = { asset: [], param: [] };
32
+ const positionals = [];
33
+
34
+ for (let i = 0; i < argv.length; i += 1) {
35
+ const arg = argv[i];
36
+
37
+ if (arg === '--') {
38
+ positionals.push(...argv.slice(i + 1));
39
+ break;
40
+ }
41
+
42
+ if (arg === '-h') {
43
+ flags.help = true;
44
+ continue;
45
+ }
46
+ if (arg === '-v') {
47
+ flags.version = true;
48
+ continue;
49
+ }
50
+
51
+ if (!arg.startsWith('--')) {
52
+ positionals.push(arg);
53
+ continue;
54
+ }
55
+
56
+ let name = arg.slice(2);
57
+ let value;
58
+ const eq = name.indexOf('=');
59
+ if (eq !== -1) {
60
+ value = name.slice(eq + 1);
61
+ name = name.slice(0, eq);
62
+ }
63
+
64
+ if (!KNOWN_FLAGS.has(name)) {
65
+ throw new UsageError(`unknown option --${name}`);
66
+ }
67
+
68
+ if (name === 'no-wait') {
69
+ flags.wait = false;
70
+ continue;
71
+ }
72
+
73
+ if (name === 'wait') {
74
+ flags.wait = value === undefined ? true : value !== 'false';
75
+ continue;
76
+ }
77
+
78
+ if (BOOLEAN_FLAGS.has(name)) {
79
+ flags[name] = value === undefined ? true : value !== 'false';
80
+ continue;
81
+ }
82
+
83
+ if (value === undefined) {
84
+ value = argv[i + 1];
85
+ if (value === undefined) throw new UsageError(`--${name} requires a value`);
86
+ i += 1;
87
+ }
88
+
89
+ if (MULTI_FLAGS.has(name)) {
90
+ multi[name].push(value);
91
+ } else {
92
+ flags[name] = value;
93
+ }
94
+ }
95
+
96
+ return { flags, positionals, assets: multi.asset, params: multi.param };
97
+ }
@@ -0,0 +1,72 @@
1
+ import crypto from 'node:crypto';
2
+
3
+ import { VERSION } from './version.mjs';
4
+ import { CliError, EXIT, log, retryDelay, sleep } from './output.mjs';
5
+ import { request } from './http.mjs';
6
+
7
+ export function signBody(secret, rawBody) {
8
+ return `sha256=${crypto.createHmac('sha256', secret).update(rawBody).digest('hex')}`;
9
+ }
10
+
11
+ /**
12
+ * POST the terminal job payload to the customer's local callback address.
13
+ * 3 retries after the first failure, waits 1s / 2s / 4s by default.
14
+ */
15
+ export async function deliverCallback(url, payload, options = {}) {
16
+ const {
17
+ secret,
18
+ maxRetries = 3,
19
+ timeoutMs = 10000,
20
+ } = options;
21
+
22
+ const raw = Buffer.from(JSON.stringify(payload));
23
+ const signature = signBody(secret, raw);
24
+ let attempts = 0;
25
+ let lastError = null;
26
+
27
+ for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
28
+ attempts += 1;
29
+ try {
30
+ const res = await request(url, {
31
+ method: 'POST',
32
+ headers: {
33
+ 'Content-Type': 'application/json',
34
+ 'X-5y-Signature': signature,
35
+ 'User-Agent': `@5y/cli/${VERSION}`,
36
+ },
37
+ body: raw,
38
+ contentLength: raw.length,
39
+ timeoutMs,
40
+ });
41
+
42
+ if (res.status >= 200 && res.status < 300) {
43
+ return { delivered: true, attempts, status: res.status };
44
+ }
45
+
46
+ lastError = new CliError({
47
+ code: 'CALLBACK_FAILED',
48
+ message: `callback endpoint returned HTTP ${res.status}`,
49
+ retryable: true,
50
+ exitCode: EXIT.UPSTREAM,
51
+ });
52
+ } catch (err) {
53
+ lastError =
54
+ err instanceof CliError
55
+ ? err
56
+ : new CliError({
57
+ code: 'CALLBACK_FAILED',
58
+ message: err && err.message ? err.message : String(err),
59
+ retryable: true,
60
+ exitCode: EXIT.UPSTREAM,
61
+ });
62
+ }
63
+
64
+ if (attempt < maxRetries) {
65
+ const wait = retryDelay(attempt);
66
+ log(`callback: delivery failed, retrying in ${wait}ms (${attempt + 1}/${maxRetries})`);
67
+ await sleep(wait);
68
+ }
69
+ }
70
+
71
+ return { delivered: false, attempts, error: lastError };
72
+ }