@dmall-inc/wd-cli 0.0.0-stage → 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.
package/lib/args.js ADDED
@@ -0,0 +1,299 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 参数解析与帮助生成(命令声明形态借鉴 oclif,help 排版借鉴 gh)。
5
+ *
6
+ * 命令声明:
7
+ * {
8
+ * id: 'skill',
9
+ * summary: '技能:列出 / 搜索 / 下载 / 安装 / 上传',
10
+ * principals: ['user', 'workspace'], // 令牌直连模式下允许的主体;user 恒可用
11
+ * commands: [
12
+ * { name: 'list', summary: '...', args: [{name:'id', required:true}],
13
+ * flags: { q: {type:'string', summary:'关键词'} },
14
+ * examples: ['wd-cli skill list --q report'],
15
+ * run: async (ctx) => {...} }
16
+ * ]
17
+ * }
18
+ */
19
+
20
+ const { CliError, EXIT } = require('./output');
21
+
22
+ /** 全局标志:所有命令可用,解析后放在 ctx.flags。 */
23
+ const GLOBAL_FLAGS = {
24
+ 'base-url': { type: 'string', summary: '平台基址,如 https://agents.example.com' },
25
+ token: { type: 'string', summary: '直连令牌(wat_ 工作空间令牌或 Agent 访问密钥),压过登录态' },
26
+ workspace: { type: 'string', summary: '本次调用使用的工作空间 id,覆盖 profile 中的选择' },
27
+ profile: { type: 'string', summary: '使用指定的配置 profile' },
28
+ 'timeout-ms': { type: 'number', summary: '请求超时毫秒数(默认 30000)' },
29
+ output: { type: 'string', short: 'o', summary: '输出格式:table | json | raw(终端默认 table,管道默认 json)' },
30
+ json: { type: 'string', summary: '只保留这些字段,逗号分隔,如 --json id,name' },
31
+ jq: { type: 'string', summary: '以内置 jq 子集过滤结果' },
32
+ envelope: { type: 'boolean', summary: '输出完整 Result(含 code / message)而不只是 data' },
33
+ quiet: { type: 'boolean', short: 'q', summary: '只输出数据,不打提示' },
34
+ verbose: { type: 'boolean', summary: '打印请求日志到标准错误(令牌自动脱敏)' },
35
+ 'no-color': { type: 'boolean', summary: '关闭彩色输出' },
36
+ 'no-principal-check': { type: 'boolean', summary: '跳过本地主体校验,直接交服务端裁决' },
37
+ yes: { type: 'boolean', short: 'y', summary: '跳过所有二次确认' },
38
+ help: { type: 'boolean', short: 'h', summary: '显示帮助' },
39
+ };
40
+
41
+ function camel(name) {
42
+ return name.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
43
+ }
44
+
45
+ /** 合并全局与命令级标志定义,建立短写索引。 */
46
+ function buildFlagIndex(commandFlags = {}) {
47
+ const defs = { ...GLOBAL_FLAGS, ...commandFlags };
48
+ const shorts = {};
49
+ for (const [name, def] of Object.entries(defs)) {
50
+ if (def.short) shorts[def.short] = name;
51
+ }
52
+ return { defs, shorts };
53
+ }
54
+
55
+ /**
56
+ * 解析 argv(已剥掉 node 与脚本路径)。
57
+ *
58
+ * 约定与 gh / kubectl 一致:资源与动作必须写在最前面(`wd-cli skill list --q x`),
59
+ * 因为只有先确定动作,才知道它自带哪些标志、各自要不要带值。
60
+ *
61
+ * @returns {{topic: ?string, command: ?string, args: string[], flags: object, wantsHelp: boolean}}
62
+ */
63
+ function parseArgv(argv, registry) {
64
+ // 1) 先定位 topic / command:取第一个 flag 之前的位置参数
65
+ const leading = [];
66
+ for (const token of argv) {
67
+ if (token.startsWith('-')) break;
68
+ leading.push(token);
69
+ }
70
+ const topicName = leading[0] || null;
71
+ const topic = topicName ? registry.topics[topicName] : null;
72
+ // 动作名允许两段(如 kb 的 "doc list"、"catalog tree"):先试长的再试短的
73
+ let commandName = null;
74
+ let commandWords = 0;
75
+ if (topic) {
76
+ const twoWord = leading[1] && leading[2] ? `${leading[1]} ${leading[2]}` : null;
77
+ if (twoWord && topic.commands.some((c) => c.name === twoWord)) {
78
+ commandName = twoWord;
79
+ commandWords = 2;
80
+ } else if (leading[1] && topic.commands.some((c) => c.name === leading[1])) {
81
+ commandName = leading[1];
82
+ commandWords = 1;
83
+ } else if (topic.commands.some((c) => c.name === '')) {
84
+ commandName = '';
85
+ commandWords = 0;
86
+ } else if (leading[1]) {
87
+ commandName = leading[1];
88
+ commandWords = 1;
89
+ }
90
+ }
91
+ // 位置参数里属于 topic/command 的个数(默认命令 '' 不占位置参数)
92
+ const consumed = (topicName ? 1 : 0) + commandWords;
93
+ const command = topic ? topic.commands.find((c) => c.name === commandName) : null;
94
+ const { defs, shorts } = buildFlagIndex(command ? command.flags : {});
95
+
96
+ // 2) 扫描全部 token
97
+ const flags = {};
98
+ const positionals = [];
99
+ let wantsHelp = false;
100
+ let i = 0;
101
+ while (i < argv.length) {
102
+ const token = argv[i];
103
+ if (token === '--') {
104
+ positionals.push(...argv.slice(i + 1));
105
+ break;
106
+ }
107
+ if (!token.startsWith('-') || token === '-') {
108
+ positionals.push(token);
109
+ i += 1;
110
+ continue;
111
+ }
112
+
113
+ let name;
114
+ let inlineValue = null;
115
+ if (token.startsWith('--')) {
116
+ const body = token.slice(2);
117
+ const eq = body.indexOf('=');
118
+ name = eq >= 0 ? body.slice(0, eq) : body;
119
+ inlineValue = eq >= 0 ? body.slice(eq + 1) : null;
120
+ // --no-xxx 关闭布尔标志(--no-color 本身是独立标志,故先查表再兜底)
121
+ if (!defs[name] && name.startsWith('no-') && defs[name.slice(3)] && defs[name.slice(3)].type === 'boolean') {
122
+ flags[camel(name.slice(3))] = false;
123
+ i += 1;
124
+ continue;
125
+ }
126
+ } else {
127
+ const short = token.slice(1);
128
+ name = shorts[short];
129
+ if (!name) {
130
+ throw new CliError(`未知选项:${token}`, EXIT.USAGE, { hint: '用 --help 查看可用选项' });
131
+ }
132
+ }
133
+
134
+ const def = defs[name];
135
+ if (!def) {
136
+ throw new CliError(`未知选项:--${name}`, EXIT.USAGE, { hint: '用 --help 查看可用选项' });
137
+ }
138
+ if (name === 'help') {
139
+ wantsHelp = true;
140
+ i += 1;
141
+ continue;
142
+ }
143
+ if (def.type === 'boolean') {
144
+ flags[camel(name)] = inlineValue === null ? true : inlineValue !== 'false';
145
+ i += 1;
146
+ continue;
147
+ }
148
+
149
+ const value = inlineValue !== null ? inlineValue : argv[i + 1];
150
+ if (value === undefined || (inlineValue === null && String(value).startsWith('-') && String(value) !== '-')) {
151
+ throw new CliError(`选项 --${name} 需要一个值`, EXIT.USAGE);
152
+ }
153
+ const parsed = def.type === 'number' ? Number(value) : value;
154
+ if (def.type === 'number' && !Number.isFinite(parsed)) {
155
+ throw new CliError(`选项 --${name} 需要一个数字`, EXIT.USAGE);
156
+ }
157
+ if (def.repeat) {
158
+ const key = camel(name);
159
+ if (!flags[key]) flags[key] = [];
160
+ flags[key].push(parsed);
161
+ } else {
162
+ flags[camel(name)] = parsed;
163
+ }
164
+ i += inlineValue !== null ? 1 : 2;
165
+ }
166
+
167
+ if (flags.output && !['table', 'json', 'raw'].includes(flags.output)) {
168
+ throw new CliError(`--output 仅支持 table | json | raw,收到:${flags.output}`, EXIT.USAGE);
169
+ }
170
+
171
+ return {
172
+ topic: topicName,
173
+ command: commandName,
174
+ args: positionals.slice(consumed),
175
+ flags,
176
+ wantsHelp,
177
+ };
178
+ }
179
+
180
+ /** 顶层帮助(gh 排版:一句话 + 分组命令 + 常用标志 + 学习入口)。 */
181
+ function renderRootHelp(registry) {
182
+ const lines = [];
183
+ lines.push('水滴平台命令行工具(wd-cli)');
184
+ lines.push('');
185
+ lines.push('用法:');
186
+ lines.push(' wd-cli <资源> <动作> [参数] [选项]');
187
+ lines.push('');
188
+ lines.push('快速开始:');
189
+ lines.push(' wd-cli auth login --base-url https://agents.example.com 登录');
190
+ lines.push(' wd-cli workspace list 看有哪些工作空间');
191
+ lines.push(' wd-cli workspace use <id> 选定当前工作空间');
192
+ lines.push(' wd-cli skill list 用起来');
193
+ lines.push('');
194
+ const groups = [
195
+ ['接入', ['auth', 'workspace', 'config']],
196
+ ['资源', ['skill', 'kb', 'agent', 'session']],
197
+ ['运营', ['credential', 'eval', 'dataset', 'trace', 'obs', 'score', 'automation', 'download-link']],
198
+ ['其它', ['api', 'completion', 'help']],
199
+ ];
200
+ for (const [label, ids] of groups) {
201
+ const rows = ids.map((id) => registry.topics[id]).filter(Boolean);
202
+ if (!rows.length) continue;
203
+ lines.push(`${label}命令:`);
204
+ const width = Math.max(...rows.map((t) => t.id.length));
205
+ for (const topic of rows) lines.push(` ${topic.id.padEnd(width)} ${topic.summary}`);
206
+ lines.push('');
207
+ }
208
+ lines.push('常用选项:');
209
+ lines.push(' -o, --output <fmt> table | json | raw');
210
+ lines.push(' --json <fields> 只输出这些字段');
211
+ lines.push(' --jq <expr> 以 jq 子集过滤');
212
+ lines.push(' --workspace <id> 本次调用使用的工作空间');
213
+ lines.push(' -q, --quiet 只输出数据');
214
+ lines.push('');
215
+ lines.push('了解更多:');
216
+ lines.push(' wd-cli <资源> --help 某个资源的全部动作');
217
+ lines.push(' wd-cli help environment 全部环境变量');
218
+ lines.push(' wd-cli help exit-codes 退出码含义');
219
+ return lines.join('\n');
220
+ }
221
+
222
+ function renderTopicHelp(topic) {
223
+ const lines = [];
224
+ lines.push(topic.summary);
225
+ if (topic.description) {
226
+ lines.push('');
227
+ lines.push(topic.description);
228
+ }
229
+ lines.push('');
230
+ lines.push('用法:');
231
+ lines.push(` wd-cli ${topic.id} <动作> [参数] [选项]`);
232
+ lines.push('');
233
+ lines.push('动作:');
234
+ const named = topic.commands.filter((c) => c.name);
235
+ const width = Math.max(...named.map((c) => c.name.length), 1);
236
+ for (const command of named) {
237
+ lines.push(` ${command.name.padEnd(width)} ${command.summary}`);
238
+ }
239
+ const examples = topic.commands.flatMap((c) => c.examples || []).slice(0, 4);
240
+ if (examples.length) {
241
+ lines.push('');
242
+ lines.push('示例:');
243
+ for (const example of examples) lines.push(` ${example}`);
244
+ }
245
+ lines.push('');
246
+ lines.push(`用 wd-cli ${topic.id} <动作> --help 查看单个动作的参数。`);
247
+ return lines.join('\n');
248
+ }
249
+
250
+ function renderCommandHelp(topic, command) {
251
+ const lines = [];
252
+ lines.push(command.summary);
253
+ if (command.description) {
254
+ lines.push('');
255
+ lines.push(command.description);
256
+ }
257
+ lines.push('');
258
+ const argsText = (command.args || [])
259
+ .map((a) => (a.required ? `<${a.name}>` : `[${a.name}]`))
260
+ .join(' ');
261
+ lines.push('用法:');
262
+ lines.push(` wd-cli ${topic.id}${command.name ? ` ${command.name}` : ''}${argsText ? ` ${argsText}` : ''} [选项]`);
263
+ if ((command.args || []).length) {
264
+ lines.push('');
265
+ lines.push('参数:');
266
+ const width = Math.max(...command.args.map((a) => a.name.length));
267
+ for (const arg of command.args) {
268
+ lines.push(` ${arg.name.padEnd(width)} ${arg.summary || ''}`);
269
+ }
270
+ }
271
+ const flags = command.flags || {};
272
+ if (Object.keys(flags).length) {
273
+ lines.push('');
274
+ lines.push('选项:');
275
+ const width = Math.max(...Object.keys(flags).map((f) => f.length));
276
+ for (const [name, def] of Object.entries(flags)) {
277
+ const short = def.short ? `-${def.short}, ` : ' ';
278
+ lines.push(` ${short}--${name.padEnd(width)} ${def.summary || ''}`);
279
+ }
280
+ }
281
+ if ((command.examples || []).length) {
282
+ lines.push('');
283
+ lines.push('示例:');
284
+ for (const example of command.examples) lines.push(` ${example}`);
285
+ }
286
+ lines.push('');
287
+ lines.push('全局选项见 wd-cli --help。');
288
+ return lines.join('\n');
289
+ }
290
+
291
+ module.exports = {
292
+ GLOBAL_FLAGS,
293
+ parseArgv,
294
+ buildFlagIndex,
295
+ camel,
296
+ renderRootHelp,
297
+ renderTopicHelp,
298
+ renderCommandHelp,
299
+ };
package/lib/auth.js ADDED
@@ -0,0 +1,77 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 主体判定与命令级校验。
5
+ *
6
+ * 服务端把 Open API 的凭据分成互斥的几类,路径前缀决定了哪类能进:
7
+ * user 统一身份登录态(本工具的默认方式)——资源可见性由「当前用户 × 当前工作空间」决定,全部命令可用
8
+ * workspace wat_ 工作空间访问令牌——只能访问技能 / 知识库这类工作空间资源
9
+ * agent Agent 访问密钥(或平台 admin 令牌)——只能访问对话 / 会话 / 凭证 / 评测 / 可观测等 Agent 类端点
10
+ *
11
+ * 本地先校验一遍,是为了把服务端那句面向开发者的 401(「工作空间令牌仅可访问工作空间资源类接口」)
12
+ * 换成用户真正需要的信息:这条命令要哪种凭据、去哪儿拿。服务端仍是最终裁决者——
13
+ * 部署方改过路径前缀配置时,用 --no-principal-check 跳过本地判断即可。
14
+ */
15
+
16
+ const { CliError, EXIT } = require('./output');
17
+
18
+ const HOW_TO_GET = {
19
+ user: '执行 wd-cli auth login 完成统一身份登录',
20
+ workspace: '在平台「工作空间 → 访问令牌」创建 wat_ 开头的令牌,再用 --token 或 WD_CLI_TOKEN 传入',
21
+ agent: '在平台 Agent 的「集成」页获取访问密钥,再用 --token 或 WD_CLI_TOKEN 传入',
22
+ };
23
+
24
+ const LABEL = {
25
+ user: '统一身份登录态',
26
+ workspace: '工作空间令牌(wat_)',
27
+ agent: 'Agent 访问密钥',
28
+ none: '未配置任何凭据',
29
+ };
30
+
31
+ /**
32
+ * 校验当前主体能否执行该命令。
33
+ *
34
+ * @param {object} runtime resolveRuntime 的结果
35
+ * @param {string} principal principalOf(runtime)
36
+ * @param {object} topic 命令组声明(principals 为令牌直连模式下允许的主体集合)
37
+ * @param {object} command 单条命令声明(可用 principals 覆盖 topic 的)
38
+ * @param {object} flags 全局标志
39
+ */
40
+ function assertPrincipalAllowed(runtime, principal, topic, command, flags = {}) {
41
+ const allowed = (command && command.principals) || (topic && topic.principals) || null;
42
+
43
+ if (principal === 'none') {
44
+ throw new CliError('未登录,也未提供令牌', EXIT.USAGE, {
45
+ hint: '先执行 wd-cli auth login,或设置 WD_CLI_TOKEN(CI 场景)',
46
+ });
47
+ }
48
+ // 登录态对所有资源命令有效:可见性交给服务端按当前工作空间裁决
49
+ if (principal === 'user') {
50
+ if (needsWorkspace(topic, command) && !runtime.workspaceId) {
51
+ throw new CliError('尚未选定工作空间', EXIT.USAGE, {
52
+ hint: '执行 wd-cli workspace list 看有哪些,再 wd-cli workspace use <id> 选一个;也可单次加 --workspace <id>',
53
+ });
54
+ }
55
+ return;
56
+ }
57
+ if (!allowed || flags.noPrincipalCheck) return;
58
+ if (allowed.includes(principal)) return;
59
+
60
+ const wanted = allowed.map((p) => LABEL[p]).join(' 或 ');
61
+ const hints = allowed.map((p) => HOW_TO_GET[p]).filter(Boolean);
62
+ hints.push(HOW_TO_GET.user);
63
+ throw new CliError(
64
+ `当前用的是${LABEL[principal]},此命令需要${wanted}`,
65
+ EXIT.USAGE,
66
+ { hint: hints.join(';或') }
67
+ );
68
+ }
69
+
70
+ /** 该命令是否需要当前工作空间(auth / config / workspace 三组自身不需要)。 */
71
+ function needsWorkspace(topic, command) {
72
+ if (command && command.workspaceOptional) return false;
73
+ if (!topic) return false;
74
+ return !['auth', 'config', 'workspace', 'help', 'completion'].includes(topic.id);
75
+ }
76
+
77
+ module.exports = { assertPrincipalAllowed, needsWorkspace, LABEL, HOW_TO_GET };