yuanflow-cli 0.1.0

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.
@@ -0,0 +1,226 @@
1
+ import { apiPost } from "../core/http.js";
2
+ import { getToken } from "../core/token.js";
3
+ import { getGlobalFlagsHelp, parseFloatNumber, parseInteger, parseJsonString } from "./shared.js";
4
+
5
+ function toFlagName(property) {
6
+ return property.replace(/_/g, "-");
7
+ }
8
+
9
+ function parsePrimitiveBySchema(name, schema, value) {
10
+ if (value === undefined) {
11
+ return undefined;
12
+ }
13
+
14
+ const type = schema?.type;
15
+ if (type === "integer") {
16
+ return parseInteger(value);
17
+ }
18
+ if (type === "number") {
19
+ return parseFloatNumber(value);
20
+ }
21
+ if (type === "boolean") {
22
+ return value === true || value === "true";
23
+ }
24
+ if (type === "object") {
25
+ if (typeof value === "string") {
26
+ return parseJsonString(value);
27
+ }
28
+ return value;
29
+ }
30
+ if (type === "array") {
31
+ if (Array.isArray(value)) {
32
+ return value;
33
+ }
34
+ if (typeof value === "string") {
35
+ const trimmed = value.trim();
36
+ if (trimmed.startsWith("[")) {
37
+ return parseJsonString(trimmed);
38
+ }
39
+ return trimmed
40
+ .split(",")
41
+ .map((item) => item.trim())
42
+ .filter(Boolean);
43
+ }
44
+ }
45
+ return value;
46
+ }
47
+
48
+ function normalizeFlagValue(name, schema, value) {
49
+ if (value === undefined) {
50
+ return undefined;
51
+ }
52
+ if (schema?.type) {
53
+ return parsePrimitiveBySchema(name, schema, value);
54
+ }
55
+ if (name.endsWith("_count") || name.endsWith("_limit") || name.endsWith("_seconds") || name === "page" || name === "page_size" || name === "top_k" || name === "sample_rate" || name === "count" || name === "image_count" || name === "copy_length" || name === "duration_seconds" || name === "ai_mode") {
56
+ return parseInteger(value);
57
+ }
58
+ if (name === "min_score") {
59
+ return parseFloatNumber(value);
60
+ }
61
+ if (name === "enable_timestamp" || name === "return_raw") {
62
+ return value === true || value === "true";
63
+ }
64
+ if (name === "constraints" || name === "context" || name === "body") {
65
+ return typeof value === "string" ? parseJsonString(value) : value;
66
+ }
67
+ return value;
68
+ }
69
+
70
+ function mapFlagsToBody(rawOptions, commandConfig, schemaProperties = {}) {
71
+ const options = { ...rawOptions };
72
+ for (const [from, to] of Object.entries(commandConfig.aliases || {})) {
73
+ if (options[from] !== undefined && options[to] === undefined) {
74
+ options[to] = options[from];
75
+ }
76
+ }
77
+
78
+ const body = {};
79
+ for (const property of Object.keys(schemaProperties)) {
80
+ const flag = toFlagName(property);
81
+ const rawValue = options[flag];
82
+ if (rawValue !== undefined) {
83
+ body[property] = normalizeFlagValue(property, schemaProperties[property], rawValue);
84
+ }
85
+ }
86
+ return body;
87
+ }
88
+
89
+ async function requireToken(context) {
90
+ const token = await getToken();
91
+ if (!token) {
92
+ return context.fail(
93
+ context.commandName,
94
+ "TOKEN_MISSING",
95
+ "缺少 YUANCHUANG_API_TOKEN",
96
+ 3,
97
+ false,
98
+ );
99
+ }
100
+ return token;
101
+ }
102
+
103
+ export function createDomainHelp(domain, registry, catalogMap) {
104
+ const items = Object.entries(registry.commands).map(([subcommand, config]) => {
105
+ const item = catalogMap.get(config.toolId);
106
+ const description = item?.description || config.description;
107
+ return ` ${subcommand.padEnd(28)} ${description}`;
108
+ });
109
+
110
+ return `${registry.title}
111
+
112
+ Usage:
113
+ ycloud ${domain} <subcommand> [flags]
114
+
115
+ Available Subcommands:
116
+ ${items.join("\n")}
117
+
118
+ ${getGlobalFlagsHelp()}`;
119
+ }
120
+
121
+ export function createToolCommandHelp(domain, subcommand, config, catalogItem) {
122
+ const properties = catalogItem?.schema?.properties || {};
123
+ const required = new Set(config.requiredFlags || []);
124
+ const propertyLines = [];
125
+ const optionalLines = [];
126
+
127
+ for (const property of Object.keys(properties)) {
128
+ const flag = `--${toFlagName(property)}`;
129
+ const type = properties[property].type || "string";
130
+ const desc = properties[property].description || "";
131
+ const line = ` ${flag} ${type}`.padEnd(28) + desc;
132
+ if (required.has(toFlagName(property))) {
133
+ propertyLines.push(line);
134
+ } else {
135
+ optionalLines.push(line);
136
+ }
137
+ }
138
+
139
+ return `${config.description}
140
+
141
+ Usage:
142
+ ycloud ${domain} ${subcommand} [flags]
143
+
144
+ Required Flags:
145
+ ${propertyLines.length ? propertyLines.join("\n") : " none"}
146
+
147
+ Optional Flags:
148
+ ${optionalLines.length ? optionalLines.join("\n") : " none"}
149
+
150
+ ${getGlobalFlagsHelp()}
151
+
152
+ Examples:
153
+ ycloud ${domain} ${subcommand} --output json
154
+
155
+ Read on success:
156
+ data
157
+
158
+ Read on error:
159
+ error.code
160
+ error.message
161
+ error.retryable`;
162
+ }
163
+
164
+ export async function executeRegisteredTool(
165
+ context,
166
+ tokens,
167
+ domain,
168
+ registry,
169
+ catalogMap,
170
+ ) {
171
+ const subcommand = tokens[0];
172
+ const config = registry.commands[subcommand];
173
+ if (!config) {
174
+ return context.fail(
175
+ context.commandName,
176
+ "UNKNOWN_COMMAND",
177
+ "未知命令",
178
+ 1,
179
+ false,
180
+ );
181
+ }
182
+
183
+ const options = context.parseCommandFlags(tokens.slice(1));
184
+ for (const requiredFlag of config.requiredFlags || []) {
185
+ const aliasSource = Object.entries(config.aliases || {}).find(
186
+ ([from, to]) => to === requiredFlag && options[from] !== undefined,
187
+ );
188
+ if (options[requiredFlag] === undefined && !aliasSource) {
189
+ return context.fail(
190
+ config.commandName,
191
+ "BAD_ARGUMENT",
192
+ `缺少必填参数 --${requiredFlag}`,
193
+ 2,
194
+ false,
195
+ );
196
+ }
197
+ }
198
+
199
+ const token = await requireToken(context);
200
+ if (typeof token !== "string") {
201
+ return token;
202
+ }
203
+
204
+ const catalogItem = catalogMap.get(config.toolId);
205
+ const body = mapFlagsToBody(
206
+ options,
207
+ config,
208
+ catalogItem?.schema?.properties || {},
209
+ );
210
+
211
+ const data = await apiPost("/v1/tools/execute", {
212
+ token,
213
+ traceId: context.globalOptions.traceId,
214
+ timeout: context.globalOptions.timeout,
215
+ baseUrl: context.globalOptions.baseUrl,
216
+ body: {
217
+ tool_id: config.toolId,
218
+ params: body,
219
+ trace_id: context.globalOptions.traceId,
220
+ },
221
+ });
222
+
223
+ return context.ok(config.commandName, data, {
224
+ tool_id: config.toolId,
225
+ });
226
+ }
@@ -0,0 +1,178 @@
1
+ import { apiGet, apiPost } from "../core/http.js";
2
+ import { getToken } from "../core/token.js";
3
+ import { getGlobalFlagsHelp, parseJsonString } from "./shared.js";
4
+
5
+ export function getToolHelp(subcommand) {
6
+ if (subcommand === "catalog") {
7
+ return `List available tool catalog
8
+
9
+ Usage:
10
+ ycloud tool catalog [flags]
11
+
12
+ Optional Flags:
13
+ none
14
+
15
+ ${getGlobalFlagsHelp()}
16
+
17
+ Examples:
18
+ ycloud tool catalog --output json
19
+
20
+ Read on success:
21
+ data.tools
22
+
23
+ Read on error:
24
+ error.code
25
+ error.message
26
+ error.retryable`;
27
+ }
28
+
29
+ if (subcommand === "execute") {
30
+ return `Execute a server-side tool
31
+
32
+ Usage:
33
+ ycloud tool execute [flags]
34
+
35
+ Required Flags:
36
+ --tool-id string tool id to execute
37
+
38
+ Optional Flags:
39
+ --params string JSON object string
40
+ --params-file string local JSON file path
41
+ --session-id string optional session id
42
+ --idempotency-key string request idempotency key
43
+
44
+ ${getGlobalFlagsHelp()}
45
+
46
+ Examples:
47
+ ycloud tool execute --tool-id copywriting_generate --params "{\"topic\":\"短视频文案\"}" --output json
48
+
49
+ Read on success:
50
+ data
51
+ meta.tool_id
52
+
53
+ Read on error:
54
+ error.code
55
+ error.message
56
+ error.retryable`;
57
+ }
58
+
59
+ return `Tool commands
60
+
61
+ Usage:
62
+ ycloud tool <catalog|execute> [flags]`;
63
+ }
64
+
65
+ function requireToken(context) {
66
+ return getToken().then((token) => {
67
+ if (!token) {
68
+ return context.fail(
69
+ context.commandName,
70
+ "TOKEN_MISSING",
71
+ "缺少 YUANCHUANG_API_TOKEN",
72
+ 3,
73
+ false,
74
+ );
75
+ }
76
+ return token;
77
+ });
78
+ }
79
+
80
+ export async function executeToolCatalog(context) {
81
+ const token = await requireToken(context);
82
+ if (typeof token !== "string") {
83
+ return token;
84
+ }
85
+ const data = await apiGet("/v1/tools/catalog", {
86
+ token,
87
+ traceId: context.globalOptions.traceId,
88
+ timeout: context.globalOptions.timeout,
89
+ baseUrl: context.globalOptions.baseUrl,
90
+ });
91
+ return context.ok("tool catalog", data);
92
+ }
93
+
94
+ export async function executeToolExecute(context, tokens, allowedToolIds = new Set()) {
95
+ const options = context.parseCommandFlags(tokens);
96
+ if (!options["tool-id"]) {
97
+ return context.fail(
98
+ "tool execute",
99
+ "BAD_ARGUMENT",
100
+ "缺少必填参数 --tool-id",
101
+ 2,
102
+ false,
103
+ );
104
+ }
105
+ if (options.params && options["params-file"]) {
106
+ return context.fail(
107
+ "tool execute",
108
+ "BAD_ARGUMENT",
109
+ "--params 和 --params-file 只能二选一",
110
+ 2,
111
+ false,
112
+ );
113
+ }
114
+ if (allowedToolIds.size > 0 && !allowedToolIds.has(options["tool-id"])) {
115
+ return context.fail(
116
+ "tool execute",
117
+ "BAD_ARGUMENT",
118
+ `tool_id 未注册到当前 CLI 暴露面: ${options["tool-id"]}`,
119
+ 2,
120
+ false,
121
+ );
122
+ }
123
+
124
+ const token = await requireToken(context);
125
+ if (typeof token !== "string") {
126
+ return token;
127
+ }
128
+
129
+ let params = undefined;
130
+ if (options.params) {
131
+ try {
132
+ params = parseJsonString(options.params);
133
+ } catch {
134
+ return context.fail(
135
+ "tool execute",
136
+ "BAD_ARGUMENT",
137
+ "--params 必须是合法 JSON",
138
+ 2,
139
+ false,
140
+ );
141
+ }
142
+ }
143
+
144
+ if (options["params-file"]) {
145
+ const { readFile } = await import("node:fs/promises");
146
+ try {
147
+ params = JSON.parse(
148
+ await readFile(options["params-file"], { encoding: "utf-8" }),
149
+ );
150
+ } catch {
151
+ return context.fail(
152
+ "tool execute",
153
+ "BAD_ARGUMENT",
154
+ "--params-file 必须是合法 JSON 文件",
155
+ 2,
156
+ false,
157
+ );
158
+ }
159
+ }
160
+
161
+ const data = await apiPost("/v1/tools/execute", {
162
+ token,
163
+ traceId: context.globalOptions.traceId,
164
+ timeout: context.globalOptions.timeout,
165
+ baseUrl: context.globalOptions.baseUrl,
166
+ body: {
167
+ tool_id: options["tool-id"],
168
+ params,
169
+ session_id: options["session-id"],
170
+ trace_id: context.globalOptions.traceId,
171
+ idempotency_key: options["idempotency-key"],
172
+ },
173
+ });
174
+
175
+ return context.ok("tool execute", data, {
176
+ tool_id: options["tool-id"],
177
+ });
178
+ }
@@ -0,0 +1,84 @@
1
+ import pkg from "../../../package.json" with { type: "json" };
2
+ import { apiGet } from "../core/http.js";
3
+ import { getToken } from "../core/token.js";
4
+ import { getGlobalFlagsHelp } from "./shared.js";
5
+
6
+ export function getVersionHelp() {
7
+ return `Check remote version update information
8
+
9
+ Usage:
10
+ ycloud version check [flags]
11
+
12
+ Optional Flags:
13
+ --app-id string application id, default ai-solovision
14
+ --platform string target platform, default desktop
15
+ --channel string release channel, default stable
16
+ --current-version string current CLI version, default local package version
17
+ --current-build int optional current build number
18
+
19
+ ${getGlobalFlagsHelp()}
20
+
21
+ Examples:
22
+ ycloud version check --output json
23
+
24
+ Read on success:
25
+ data.latest_version
26
+ data.update_available
27
+ data.update_type
28
+
29
+ Read on error:
30
+ error.code
31
+ error.message`;
32
+ }
33
+
34
+ export async function executeVersionCheck(context, tokens) {
35
+ const token = await getToken();
36
+ if (!token) {
37
+ return context.fail(
38
+ "version check",
39
+ "TOKEN_MISSING",
40
+ "缺少 YUANCHUANG_API_TOKEN",
41
+ 3,
42
+ false,
43
+ );
44
+ }
45
+
46
+ const options = context.parseCommandFlags(tokens);
47
+ const appId = options["app-id"] || "ai-solovision";
48
+ const platform = options.platform || "desktop";
49
+ const channel = options.channel || "stable";
50
+ const currentVersion = options["current-version"] || pkg.version;
51
+ const query = new URLSearchParams({
52
+ app_id: appId,
53
+ platform,
54
+ channel,
55
+ current_version: currentVersion,
56
+ });
57
+
58
+ if (options["current-build"] !== undefined) {
59
+ query.set("current_build", String(options["current-build"]));
60
+ }
61
+
62
+ const data = await apiGet(`/v1/version/check?${query.toString()}`, {
63
+ token,
64
+ traceId: context.globalOptions.traceId,
65
+ timeout: context.globalOptions.timeout,
66
+ baseUrl: context.globalOptions.baseUrl,
67
+ });
68
+
69
+ const remoteData = data?.data || data || {};
70
+ return context.ok("version check", {
71
+ app_id: appId,
72
+ platform,
73
+ channel,
74
+ current_version: currentVersion,
75
+ current_build: remoteData.current_build ?? null,
76
+ latest_version: remoteData.latest_version ?? null,
77
+ latest_build: remoteData.latest_build ?? null,
78
+ update_available: Boolean(remoteData.update_available),
79
+ update_type: remoteData.update_type || "none",
80
+ checked_at: remoteData.checked_at || null,
81
+ release: remoteData.release || null,
82
+ raw: data,
83
+ });
84
+ }
@@ -0,0 +1,78 @@
1
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ const CONFIG_DIR_NAME = ".yuanflow";
6
+ const CONFIG_FILE_NAME = "config.json";
7
+
8
+ function getUserHomeDir() {
9
+ return process.env.USERPROFILE || process.env.HOME || homedir();
10
+ }
11
+
12
+ export function getConfigDir() {
13
+ return join(getUserHomeDir(), CONFIG_DIR_NAME);
14
+ }
15
+
16
+ export function getConfigPath() {
17
+ return join(getConfigDir(), CONFIG_FILE_NAME);
18
+ }
19
+
20
+ export async function readConfig() {
21
+ try {
22
+ const content = await readFile(getConfigPath(), "utf8");
23
+ return JSON.parse(content);
24
+ } catch (error) {
25
+ if (error?.code === "ENOENT") {
26
+ return {};
27
+ }
28
+ throw error;
29
+ }
30
+ }
31
+
32
+ export async function writeConfig(config) {
33
+ await mkdir(getConfigDir(), { recursive: true });
34
+ await writeFile(
35
+ getConfigPath(),
36
+ `${JSON.stringify(config, null, 2)}\n`,
37
+ "utf8",
38
+ );
39
+ }
40
+
41
+ export async function updateConfig(partial) {
42
+ const current = await readConfig();
43
+ const next = {
44
+ ...current,
45
+ ...partial,
46
+ };
47
+ await writeConfig(next);
48
+ return next;
49
+ }
50
+
51
+ export async function clearConfigKey(key) {
52
+ const current = await readConfig();
53
+ if (!(key in current)) {
54
+ return current;
55
+ }
56
+ const next = { ...current };
57
+ delete next[key];
58
+ if (Object.keys(next).length === 0) {
59
+ try {
60
+ await rm(getConfigPath(), { force: true });
61
+ } catch {
62
+ return {};
63
+ }
64
+ return {};
65
+ }
66
+ await writeConfig(next);
67
+ return next;
68
+ }
69
+
70
+ export function maskToken(token) {
71
+ if (!token) {
72
+ return null;
73
+ }
74
+ if (token.length <= 8) {
75
+ return `${token.slice(0, 2)}****`;
76
+ }
77
+ return `${token.slice(0, 7)}****${token.slice(-4)}`;
78
+ }
@@ -0,0 +1,133 @@
1
+ const DEFAULT_BASE_URL = "https://api.yuanchuangai.com";
2
+ const DEFAULT_OPENAPI_URL = "https://api.yuanchuangai.com/openapi.json";
3
+
4
+ function normalizeBaseUrl(baseUrl) {
5
+ return (baseUrl || process.env.YUANCHUANG_API_BASE_URL || DEFAULT_BASE_URL)
6
+ .trim()
7
+ .replace(/\/+$/, "");
8
+ }
9
+
10
+ function buildHeaders(token, traceId) {
11
+ const headers = {
12
+ Accept: "application/json",
13
+ };
14
+ if (token) {
15
+ headers.Authorization = `Bearer ${token}`;
16
+ }
17
+ if (traceId) {
18
+ headers["X-Trace-Id"] = traceId;
19
+ }
20
+ return headers;
21
+ }
22
+
23
+ function createTimeoutSignal(timeout) {
24
+ const timeoutMs = timeout ? Number.parseInt(String(timeout), 10) : undefined;
25
+ if (!timeoutMs || Number.isNaN(timeoutMs) || timeoutMs <= 0) {
26
+ return undefined;
27
+ }
28
+ return AbortSignal.timeout(timeoutMs);
29
+ }
30
+
31
+ function parseResponseBody(text) {
32
+ if (!text) {
33
+ return null;
34
+ }
35
+ try {
36
+ return JSON.parse(text);
37
+ } catch {
38
+ return text;
39
+ }
40
+ }
41
+
42
+ function mapStatusToCode(status) {
43
+ if (status === 401 || status === 403) {
44
+ return { code: "AUTH_INVALID", exitCode: 3, retryable: false };
45
+ }
46
+ if (status === 400 || status === 404 || status === 422) {
47
+ return { code: "BAD_ARGUMENT", exitCode: 2, retryable: false };
48
+ }
49
+ if (status >= 500) {
50
+ return { code: "UPSTREAM_ERROR", exitCode: 4, retryable: true };
51
+ }
52
+ return { code: "UPSTREAM_ERROR", exitCode: 4, retryable: false };
53
+ }
54
+
55
+ async function request(method, path, options = {}) {
56
+ const headers = buildHeaders(options.token, options.traceId);
57
+ const init = {
58
+ method,
59
+ headers,
60
+ signal: createTimeoutSignal(options.timeout),
61
+ };
62
+
63
+ if (options.body !== undefined) {
64
+ headers["Content-Type"] = "application/json";
65
+ init.body = JSON.stringify(options.body);
66
+ }
67
+
68
+ try {
69
+ const response = await fetch(`${normalizeBaseUrl(options.baseUrl)}${path}`, init);
70
+ const text = await response.text();
71
+ const payload = parseResponseBody(text);
72
+
73
+ if (!response.ok) {
74
+ const mapped = mapStatusToCode(response.status);
75
+ const message =
76
+ payload?.detail ||
77
+ payload?.message ||
78
+ payload?.error?.message ||
79
+ `HTTP ${response.status}`;
80
+ const error = new Error(message);
81
+ error.code = mapped.code;
82
+ error.exitCode = mapped.exitCode;
83
+ error.retryable = mapped.retryable;
84
+ throw error;
85
+ }
86
+
87
+ return payload;
88
+ } catch (error) {
89
+ if (error.name === "AbortError") {
90
+ const timeoutError = new Error("请求超时");
91
+ timeoutError.code = "UPSTREAM_TIMEOUT";
92
+ timeoutError.exitCode = 5;
93
+ timeoutError.retryable = true;
94
+ throw timeoutError;
95
+ }
96
+ if (error.code) {
97
+ throw error;
98
+ }
99
+ const networkError = new Error(error.message || "网络请求失败");
100
+ networkError.code = "NETWORK_ERROR";
101
+ networkError.exitCode = 5;
102
+ networkError.retryable = true;
103
+ throw networkError;
104
+ }
105
+ }
106
+
107
+ export async function apiGet(path, options = {}) {
108
+ return request("GET", path, options);
109
+ }
110
+
111
+ export async function apiPost(path, options = {}) {
112
+ return request("POST", path, options);
113
+ }
114
+
115
+ export async function fetchOpenApiSpec(options = {}) {
116
+ const response = await fetch(DEFAULT_OPENAPI_URL, {
117
+ method: "GET",
118
+ headers: {
119
+ Accept: "application/json",
120
+ },
121
+ signal: createTimeoutSignal(options.timeout),
122
+ });
123
+
124
+ if (!response.ok) {
125
+ const error = new Error(`HTTP ${response.status}`);
126
+ error.code = "UPSTREAM_ERROR";
127
+ error.exitCode = 4;
128
+ error.retryable = true;
129
+ throw error;
130
+ }
131
+
132
+ return response.json();
133
+ }