@dmall-inc/wd-cli 0.0.0-stage → 0.2.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/README.md +401 -2
- package/bin/wd-cli.js +106 -0
- package/docs/design-references.md +75 -0
- package/lib/args.js +299 -0
- package/lib/auth.js +77 -0
- package/lib/commands/agent.js +784 -0
- package/lib/commands/api.js +122 -0
- package/lib/commands/auth.js +314 -0
- package/lib/commands/automation.js +92 -0
- package/lib/commands/completion.js +141 -0
- package/lib/commands/config.js +120 -0
- package/lib/commands/credential.js +108 -0
- package/lib/commands/dataset.js +144 -0
- package/lib/commands/evaluate.js +170 -0
- package/lib/commands/help.js +81 -0
- package/lib/commands/index.js +46 -0
- package/lib/commands/kb.js +449 -0
- package/lib/commands/observability.js +381 -0
- package/lib/commands/session.js +189 -0
- package/lib/commands/skill.js +463 -0
- package/lib/commands/workspace.js +110 -0
- package/lib/config.js +269 -0
- package/lib/data.js +128 -0
- package/lib/http.js +402 -0
- package/lib/jq.js +342 -0
- package/lib/keyring.js +125 -0
- package/lib/oidc.js +344 -0
- package/lib/output.js +249 -0
- package/package.json +22 -4
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 通用逃生口(形态对标 gh api)。
|
|
5
|
+
*
|
|
6
|
+
* 平台上了新端点、或某个端点还没被包成子命令时,用它直接打:
|
|
7
|
+
* wd-cli api /skills
|
|
8
|
+
* wd-cli api /datasets/66 -X POST -f name=回归集 -F size=100
|
|
9
|
+
* wd-cli api /skills/import -F file=@a.zip -f skillType=personal
|
|
10
|
+
* wd-cli api /skills/search -f q=report --paginate --output json
|
|
11
|
+
*
|
|
12
|
+
* 鉴权头与工作空间头自动带上;本地不做主体校验,一切交服务端裁决。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const http = require('../http');
|
|
16
|
+
const data = require('../data');
|
|
17
|
+
const output = require('../output');
|
|
18
|
+
const { CliError, EXIT } = output;
|
|
19
|
+
|
|
20
|
+
const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'];
|
|
21
|
+
|
|
22
|
+
const run = {
|
|
23
|
+
name: '',
|
|
24
|
+
summary: '对任意 Open API 路径发起带鉴权的请求',
|
|
25
|
+
args: [{ name: 'path', required: true, summary: '相对 /api/open 的路径(以 / 开头),或完整 URL' }],
|
|
26
|
+
flags: {
|
|
27
|
+
method: {
|
|
28
|
+
type: 'string',
|
|
29
|
+
short: 'X',
|
|
30
|
+
summary: `HTTP 方法(${METHODS.join(' / ')});给了字段而未指定时默认 POST`,
|
|
31
|
+
},
|
|
32
|
+
field: { type: 'string', short: 'f', repeat: true, summary: 'key=value 字符串字段(可重复)' },
|
|
33
|
+
'typed-field': {
|
|
34
|
+
type: 'string',
|
|
35
|
+
short: 'F',
|
|
36
|
+
repeat: true,
|
|
37
|
+
summary: 'key=value 带类型推断的字段,值可用 @file 读文件(可重复)',
|
|
38
|
+
},
|
|
39
|
+
header: { type: 'string', short: 'H', repeat: true, summary: '附加请求头 "key: value"(可重复)' },
|
|
40
|
+
input: { type: 'string', summary: '请求体:文件路径或 -(标准输入)' },
|
|
41
|
+
paginate: { type: 'boolean', summary: '对分页响应自动翻页并合并 list' },
|
|
42
|
+
},
|
|
43
|
+
examples: [
|
|
44
|
+
'wd-cli api /skills',
|
|
45
|
+
'wd-cli api /diwork/message-channels --output json',
|
|
46
|
+
'wd-cli api /datasets/66 -X POST -f name=回归集 -F enabled=true',
|
|
47
|
+
'wd-cli api /skills/import -F file=@my-skill.zip -f skillType=personal',
|
|
48
|
+
],
|
|
49
|
+
skipPrincipalCheck: true,
|
|
50
|
+
workspaceOptional: true,
|
|
51
|
+
async run(ctx) {
|
|
52
|
+
const flags = ctx.flags;
|
|
53
|
+
const target = String(ctx.args[0]);
|
|
54
|
+
const stringFields = data.parseKeyValues(flags.field, { typed: false, label: '-f' });
|
|
55
|
+
const typedEntries = flags.typedField || [];
|
|
56
|
+
const headers = data.parseHeaders(flags.header);
|
|
57
|
+
|
|
58
|
+
// -F 的值支持 @file:有文件即走 multipart
|
|
59
|
+
const typedFields = {};
|
|
60
|
+
const files = [];
|
|
61
|
+
for (const item of typedEntries) {
|
|
62
|
+
const text = String(item);
|
|
63
|
+
const eq = text.indexOf('=');
|
|
64
|
+
if (eq <= 0) throw new CliError(`-F 需要 key=value 形式,收到:${text}`, EXIT.USAGE);
|
|
65
|
+
const key = text.slice(0, eq);
|
|
66
|
+
const raw = text.slice(eq + 1);
|
|
67
|
+
if (raw.startsWith('@')) files.push({ name: key, path: raw.slice(1) });
|
|
68
|
+
else typedFields[key] = data.inferTypedValue(raw);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const hasBodyInput = flags.input !== undefined;
|
|
72
|
+
const hasFields = Object.keys(stringFields).length > 0 || Object.keys(typedFields).length > 0 || files.length > 0;
|
|
73
|
+
const method = (flags.method || (hasFields || hasBodyInput ? 'POST' : 'GET')).toUpperCase();
|
|
74
|
+
if (!METHODS.includes(method)) {
|
|
75
|
+
throw new CliError(`不支持的方法:${method}`, EXIT.USAGE, { hint: `可用:${METHODS.join(' / ')}` });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const isQueryMethod = method === 'GET' || method === 'DELETE';
|
|
79
|
+
const absolute = /^https?:\/\//i.test(target);
|
|
80
|
+
const base = absolute ? '' : ctx.apiBase();
|
|
81
|
+
const pathname = absolute ? target : target.startsWith('/') ? target : `/${target}`;
|
|
82
|
+
|
|
83
|
+
const options = { method, base, path: pathname, headers };
|
|
84
|
+
if (isQueryMethod) {
|
|
85
|
+
options.query = { ...stringFields, ...typedFields };
|
|
86
|
+
if (files.length) throw new CliError(`${method} 请求不支持 @file 字段`, EXIT.USAGE);
|
|
87
|
+
} else if (files.length) {
|
|
88
|
+
options.form = http.buildFormData({ ...stringFields, ...typedFields }, files);
|
|
89
|
+
} else if (hasBodyInput) {
|
|
90
|
+
options.body = data.readDataText(flags.input, '--input');
|
|
91
|
+
} else if (hasFields) {
|
|
92
|
+
options.body = { ...stringFields, ...typedFields };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// raw 为默认:api 是逃生口,不该替用户猜响应形状
|
|
96
|
+
const wantsStructured = flags.output === 'json' || flags.json || flags.jq || flags.paginate || flags.envelope;
|
|
97
|
+
if (!wantsStructured && !output.isTty(process.stdout)) {
|
|
98
|
+
// 管道里也按 raw 直出,保持「所见即服务端所发」
|
|
99
|
+
const text = await http.request(ctx, { ...options, raw: true });
|
|
100
|
+
process.stdout.write(text.endsWith('\n') ? text : `${text}\n`);
|
|
101
|
+
return EXIT.OK;
|
|
102
|
+
}
|
|
103
|
+
if (!wantsStructured) {
|
|
104
|
+
const text = await http.request(ctx, { ...options, raw: true });
|
|
105
|
+
process.stdout.write(text.endsWith('\n') ? text : `${text}\n`);
|
|
106
|
+
return EXIT.OK;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const result = flags.paginate
|
|
110
|
+
? await http.requestAllPages(ctx, options)
|
|
111
|
+
: await http.request(ctx, options);
|
|
112
|
+
output.print(result, { flags });
|
|
113
|
+
return EXIT.OK;
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
module.exports = {
|
|
118
|
+
id: 'api',
|
|
119
|
+
summary: '直接调用任意 Open API 路径(逃生口)',
|
|
120
|
+
description: '新端点上线后无需等 CLI 发版;所有资源子命令都等价于某一条 api 调用。',
|
|
121
|
+
commands: [run],
|
|
122
|
+
};
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 登录、状态、登出(命令族与文案对标 gh auth;登录流程对标 gcloud auth login)。
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const config = require('../config');
|
|
8
|
+
const oidc = require('../oidc');
|
|
9
|
+
const http = require('../http');
|
|
10
|
+
const output = require('../output');
|
|
11
|
+
const { CliError, EXIT } = output;
|
|
12
|
+
|
|
13
|
+
/** 拉登录配置:免鉴权端点,CLI 此刻还没有任何凭据。 */
|
|
14
|
+
async function fetchLoginConfig(baseUrl, timeoutMs) {
|
|
15
|
+
const url = `${config.trimSlash(baseUrl)}/api/open/auth/login-config`;
|
|
16
|
+
const response = await http.fetchWithTimeout(url, { method: 'GET', headers: { Accept: 'application/json' } }, timeoutMs);
|
|
17
|
+
const text = await response.text();
|
|
18
|
+
let json = null;
|
|
19
|
+
try {
|
|
20
|
+
json = JSON.parse(text);
|
|
21
|
+
} catch {
|
|
22
|
+
json = null;
|
|
23
|
+
}
|
|
24
|
+
if (!response.ok || !json) {
|
|
25
|
+
throw new CliError(`无法获取登录配置(HTTP ${response.status}):${url}`, EXIT.NETWORK, {
|
|
26
|
+
hint: '确认 --base-url 指向平台对外地址,且该地址能访问 /api/open',
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
if (typeof json.code === 'number' && json.code !== http.RESULT_OK) {
|
|
30
|
+
throw new CliError(json.message || '平台未开启统一登录', EXIT.BUSINESS, {
|
|
31
|
+
code: json.code,
|
|
32
|
+
errorCode: json.errorCode,
|
|
33
|
+
hint: '联系平台管理员确认统一身份平台已配置(idp.rp.auth-base-url)',
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
return json.data;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 主体自省。
|
|
41
|
+
*
|
|
42
|
+
* @param {object} [options]
|
|
43
|
+
* @param {boolean} [options.withWorkspace=true] 是否带当前工作空间头。登录时的自检传 false:
|
|
44
|
+
* whoami 本就允许缺省工作空间,而 profile 里残留的工作空间可能已失效(换了环境、被移出),
|
|
45
|
+
* 带上它会让一次成功的登录以 NOT_WORKSPACE_MEMBER 收场。
|
|
46
|
+
*/
|
|
47
|
+
async function whoami(ctx, { withWorkspace = true } = {}) {
|
|
48
|
+
const target = withWorkspace
|
|
49
|
+
? ctx
|
|
50
|
+
: new http.Context({
|
|
51
|
+
runtime: { ...ctx.runtime, workspaceId: null },
|
|
52
|
+
principal: ctx.principal,
|
|
53
|
+
flags: ctx.flags,
|
|
54
|
+
env: ctx.env,
|
|
55
|
+
});
|
|
56
|
+
return http.request(target, { method: 'GET', path: '/auth/whoami' });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 登录后还没有当前工作空间时:只属于一个就直接选上(省掉一次 workspace use),
|
|
61
|
+
* 多个则提示去选。取列表失败不影响登录,退回通用提示。
|
|
62
|
+
* 只数可用(active)的工作空间——停用的选上了也用不了。
|
|
63
|
+
*/
|
|
64
|
+
async function settleWorkspace(ctx, profileName) {
|
|
65
|
+
let items;
|
|
66
|
+
try {
|
|
67
|
+
items = await http.request(ctx, { method: 'GET', path: '/workspaces' });
|
|
68
|
+
} catch {
|
|
69
|
+
return { kind: 'unknown' };
|
|
70
|
+
}
|
|
71
|
+
const usable = (Array.isArray(items) ? items : []).filter((w) => !w.status || w.status === 'active');
|
|
72
|
+
if (usable.length === 1) {
|
|
73
|
+
const only = usable[0];
|
|
74
|
+
config.updateProfile(profileName, { workspaceId: String(only.id), workspaceName: only.name }, ctx.env);
|
|
75
|
+
return { kind: 'picked', workspace: only };
|
|
76
|
+
}
|
|
77
|
+
return { kind: usable.length ? 'many' : 'none', count: usable.length };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const login = {
|
|
81
|
+
name: 'login',
|
|
82
|
+
summary: '统一身份登录(浏览器授权码 + PKCE)',
|
|
83
|
+
description:
|
|
84
|
+
'在本机起一个临时回调服务,打开浏览器完成统一身份登录,把令牌存到本地配置。\n' +
|
|
85
|
+
'无浏览器环境(SSH / 容器)加 --no-browser:打印授权地址,登录后把回调地址贴回来。',
|
|
86
|
+
flags: {
|
|
87
|
+
'no-browser': { type: 'boolean', summary: '不自动开浏览器,改为打印地址并等待粘贴回调' },
|
|
88
|
+
'no-verify': { type: 'boolean', summary: '跳过登录后的 whoami 自检' },
|
|
89
|
+
},
|
|
90
|
+
examples: [
|
|
91
|
+
'wd-cli auth login --base-url https://agents.example.com',
|
|
92
|
+
'wd-cli auth login --profile prod --base-url https://agents.example.com',
|
|
93
|
+
'wd-cli auth login --no-browser',
|
|
94
|
+
],
|
|
95
|
+
skipPrincipalCheck: true,
|
|
96
|
+
async run(ctx) {
|
|
97
|
+
const flags = ctx.flags;
|
|
98
|
+
const baseUrl = ctx.runtime.baseUrl;
|
|
99
|
+
if (!baseUrl) {
|
|
100
|
+
throw new CliError('未指定平台基址', EXIT.USAGE, {
|
|
101
|
+
hint: '加 --base-url https://<平台域名>,或设置 WD_CLI_BASE_URL',
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
const profileName = ctx.runtime.profileName;
|
|
105
|
+
const loginConfig = await fetchLoginConfig(baseUrl, ctx.timeoutMs);
|
|
106
|
+
const clientId = loginConfig.clientId;
|
|
107
|
+
const scopes = loginConfig.scopes || ['openid', 'profile'];
|
|
108
|
+
|
|
109
|
+
const pkce = oidc.createPkce();
|
|
110
|
+
const state = oidc.randomToken(24);
|
|
111
|
+
const nonce = oidc.randomToken(24);
|
|
112
|
+
|
|
113
|
+
let code;
|
|
114
|
+
let redirectUri;
|
|
115
|
+
let server = null;
|
|
116
|
+
try {
|
|
117
|
+
if (flags.noBrowser) {
|
|
118
|
+
// 回贴模式:认证中心仍按回环地址校验,端口随便给一个(不会真的被访问)
|
|
119
|
+
redirectUri = `http://${oidc.REGISTERED_REDIRECT_HOST}:0${oidc.CALLBACK_PATH}`;
|
|
120
|
+
const authorizeUrl = oidc.buildAuthorizeUrl({
|
|
121
|
+
authorizeEndpoint: loginConfig.authorizeEndpoint,
|
|
122
|
+
clientId,
|
|
123
|
+
redirectUri,
|
|
124
|
+
scopes,
|
|
125
|
+
state,
|
|
126
|
+
nonce,
|
|
127
|
+
challenge: pkce.challenge,
|
|
128
|
+
});
|
|
129
|
+
output.info('在任意浏览器打开下面的地址完成登录:', flags);
|
|
130
|
+
output.info(`\n ${authorizeUrl}\n`, flags);
|
|
131
|
+
code = await oidc.promptForCallbackUrl(state);
|
|
132
|
+
} else {
|
|
133
|
+
server = await oidc.startLoopbackServer(state);
|
|
134
|
+
redirectUri = server.redirectUri;
|
|
135
|
+
const authorizeUrl = oidc.buildAuthorizeUrl({
|
|
136
|
+
authorizeEndpoint: loginConfig.authorizeEndpoint,
|
|
137
|
+
clientId,
|
|
138
|
+
redirectUri,
|
|
139
|
+
scopes,
|
|
140
|
+
state,
|
|
141
|
+
nonce,
|
|
142
|
+
challenge: pkce.challenge,
|
|
143
|
+
});
|
|
144
|
+
// 地址一律打出来:浏览器开错了、开在别的 profile 里,用户还能自己复制
|
|
145
|
+
output.info(`授权地址:\n\n ${authorizeUrl}\n`, flags);
|
|
146
|
+
const opened = await oidc.openBrowser(authorizeUrl, ctx.env);
|
|
147
|
+
output.info(
|
|
148
|
+
opened ? '已在浏览器打开登录页,完成登录后自动返回…' : '请在浏览器打开上面的地址完成登录…',
|
|
149
|
+
flags
|
|
150
|
+
);
|
|
151
|
+
code = await server.waitForCode();
|
|
152
|
+
}
|
|
153
|
+
} finally {
|
|
154
|
+
if (server) await server.close();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const tokens = await oidc.exchangeCode(
|
|
158
|
+
{
|
|
159
|
+
tokenEndpoint: loginConfig.tokenEndpoint,
|
|
160
|
+
clientId,
|
|
161
|
+
code,
|
|
162
|
+
verifier: pkce.verifier,
|
|
163
|
+
redirectUri,
|
|
164
|
+
},
|
|
165
|
+
ctx.timeoutMs
|
|
166
|
+
);
|
|
167
|
+
const idPayload = oidc.assertIdToken(tokens.idToken, { nonce, clientId });
|
|
168
|
+
|
|
169
|
+
const auth = {
|
|
170
|
+
accessToken: tokens.accessToken,
|
|
171
|
+
refreshToken: tokens.refreshToken,
|
|
172
|
+
expiresAt: tokens.expiresAt,
|
|
173
|
+
subject: idPayload ? idPayload.sub : null,
|
|
174
|
+
name: idPayload ? idPayload.name || idPayload.email || null : null,
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
// 换了平台地址 = 换了环境:工作空间 id 与对话地址都只在原环境有意义,一并清掉。
|
|
178
|
+
// 不清的话,残留的工作空间会让后续命令报「非该工作空间成员」,残留的 chatBaseUrl
|
|
179
|
+
// 更隐蔽——对话会悄悄打到旧环境。
|
|
180
|
+
const previousBaseUrl = config.trimSlash((ctx.runtime.profile || {}).baseUrl || '');
|
|
181
|
+
const switchedEnv = Boolean(previousBaseUrl) && previousBaseUrl !== config.trimSlash(baseUrl);
|
|
182
|
+
const envBound = switchedEnv ? { workspaceId: null, workspaceName: null, chatBaseUrl: null } : {};
|
|
183
|
+
|
|
184
|
+
// 配置与凭据分文件:前者可以进 dotfiles,后者 0600
|
|
185
|
+
config.updateProfile(
|
|
186
|
+
profileName,
|
|
187
|
+
{
|
|
188
|
+
baseUrl,
|
|
189
|
+
authBaseUrl: loginConfig.authBaseUrl,
|
|
190
|
+
clientId,
|
|
191
|
+
...envBound,
|
|
192
|
+
...(ctx.flags.chatBaseUrl ? { chatBaseUrl: ctx.flags.chatBaseUrl } : {}),
|
|
193
|
+
},
|
|
194
|
+
ctx.env
|
|
195
|
+
);
|
|
196
|
+
config.setCurrentProfile(profileName, ctx.env);
|
|
197
|
+
config.updateHostEntry(profileName, { auth, token: null }, ctx.env);
|
|
198
|
+
|
|
199
|
+
ctx.runtime = config.resolveRuntime(ctx.flags, ctx.env);
|
|
200
|
+
ctx.principal = 'user';
|
|
201
|
+
|
|
202
|
+
let displayName = auth.name || auth.subject || '';
|
|
203
|
+
if (!flags.noVerify) {
|
|
204
|
+
const me = await whoami(ctx, { withWorkspace: false });
|
|
205
|
+
displayName = (me && (me.username || me.userId)) || displayName;
|
|
206
|
+
}
|
|
207
|
+
output.success(`已登录:${displayName}(profile ${profileName})`, flags);
|
|
208
|
+
if (switchedEnv) {
|
|
209
|
+
output.info(`平台地址已从 ${previousBaseUrl} 切换,原工作空间与对话地址属于旧环境,已清除`, flags);
|
|
210
|
+
}
|
|
211
|
+
if (ctx.runtime.workspaceId) {
|
|
212
|
+
const label = ctx.runtime.workspaceName ? `${ctx.runtime.workspaceName} (${ctx.runtime.workspaceId})` : ctx.runtime.workspaceId;
|
|
213
|
+
output.info(`当前工作空间:${label};要换用 wd-cli workspace use <id>`, flags);
|
|
214
|
+
return EXIT.OK;
|
|
215
|
+
}
|
|
216
|
+
const pickHint = '用 wd-cli workspace list 看有哪些工作空间,再 wd-cli workspace use <id> 选一个';
|
|
217
|
+
const settled = flags.noVerify ? { kind: 'unknown' } : await settleWorkspace(ctx, profileName);
|
|
218
|
+
if (settled.kind === 'picked') {
|
|
219
|
+
output.info(`你只属于一个工作空间,已自动选定:${settled.workspace.name} (${settled.workspace.id})`, flags);
|
|
220
|
+
} else if (settled.kind === 'many') {
|
|
221
|
+
output.info(`你属于 ${settled.count} 个工作空间,${pickHint}`, flags);
|
|
222
|
+
} else if (settled.kind === 'none') {
|
|
223
|
+
output.warn('你还不属于任何工作空间,请联系工作空间管理员邀请你加入', flags);
|
|
224
|
+
} else {
|
|
225
|
+
output.info(`下一步:${pickHint}`, flags);
|
|
226
|
+
}
|
|
227
|
+
return EXIT.OK;
|
|
228
|
+
},
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
const status = {
|
|
232
|
+
name: 'status',
|
|
233
|
+
summary: '查看当前登录状态与生效配置',
|
|
234
|
+
examples: ['wd-cli auth status', 'wd-cli auth status --output json'],
|
|
235
|
+
skipPrincipalCheck: true,
|
|
236
|
+
workspaceOptional: true,
|
|
237
|
+
async run(ctx) {
|
|
238
|
+
const runtime = ctx.runtime;
|
|
239
|
+
const principal = ctx.principal;
|
|
240
|
+
const rows = {
|
|
241
|
+
profile: runtime.profileName,
|
|
242
|
+
principal,
|
|
243
|
+
baseUrl: runtime.baseUrl || '(未配置)',
|
|
244
|
+
workspaceId: runtime.workspaceId || '(未选定)',
|
|
245
|
+
workspaceName: runtime.workspaceName || '',
|
|
246
|
+
};
|
|
247
|
+
if (runtime.directToken) {
|
|
248
|
+
rows.token = config.maskToken(runtime.directToken);
|
|
249
|
+
rows.tokenSource = ctx.flags.token ? '--token' : ctx.env.WD_CLI_TOKEN ? 'WD_CLI_TOKEN' : 'hosts.json';
|
|
250
|
+
} else if (runtime.auth) {
|
|
251
|
+
rows.accessToken = config.maskToken(runtime.auth.accessToken);
|
|
252
|
+
rows.refreshToken = config.maskToken(runtime.auth.refreshToken);
|
|
253
|
+
rows.expiresAt = runtime.auth.expiresAt ? new Date(runtime.auth.expiresAt).toISOString() : '(未知)';
|
|
254
|
+
rows.authBaseUrl = runtime.authBaseUrl || '(未配置)';
|
|
255
|
+
rows.clientId = runtime.clientId || '(未配置)';
|
|
256
|
+
rows.tokenStorage = config.keyring.describe(ctx.env);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
if (principal === 'none') {
|
|
260
|
+
output.print(rows, { flags: ctx.flags });
|
|
261
|
+
output.warn('尚未登录:执行 wd-cli auth login,或设置 WD_CLI_TOKEN', ctx.flags);
|
|
262
|
+
return EXIT.OK;
|
|
263
|
+
}
|
|
264
|
+
if (runtime.baseUrl) {
|
|
265
|
+
try {
|
|
266
|
+
const me = await whoami(ctx);
|
|
267
|
+
rows.serverPrincipal = me.principal;
|
|
268
|
+
if (me.username) rows.username = me.username;
|
|
269
|
+
if (me.userId) rows.userId = me.userId;
|
|
270
|
+
if (me.agentId) rows.agentId = me.agentId;
|
|
271
|
+
if (me.workspaceId) rows.serverWorkspaceId = me.workspaceId;
|
|
272
|
+
} catch (error) {
|
|
273
|
+
output.warn(`自检失败:${error.message}`, ctx.flags);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
output.print(rows, { flags: ctx.flags });
|
|
277
|
+
return EXIT.OK;
|
|
278
|
+
},
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
const logout = {
|
|
282
|
+
name: 'logout',
|
|
283
|
+
summary: '退出登录:撤销令牌并清除本地凭据',
|
|
284
|
+
examples: ['wd-cli auth logout', 'wd-cli auth logout --profile prod'],
|
|
285
|
+
skipPrincipalCheck: true,
|
|
286
|
+
workspaceOptional: true,
|
|
287
|
+
async run(ctx) {
|
|
288
|
+
const profileName = ctx.runtime.profileName;
|
|
289
|
+
const auth = ctx.runtime.auth;
|
|
290
|
+
if (auth && auth.refreshToken && ctx.runtime.authBaseUrl) {
|
|
291
|
+
const revoked = await oidc.revokeToken(
|
|
292
|
+
{
|
|
293
|
+
revokeEndpoint: `${ctx.runtime.authBaseUrl}/oauth2/revoke`,
|
|
294
|
+
clientId: ctx.runtime.clientId,
|
|
295
|
+
token: auth.refreshToken,
|
|
296
|
+
},
|
|
297
|
+
ctx.timeoutMs
|
|
298
|
+
);
|
|
299
|
+
if (!revoked) output.warn('认证中心撤销令牌未成功,仅清除了本地凭据', ctx.flags);
|
|
300
|
+
}
|
|
301
|
+
config.updateHostEntry(profileName, { auth: null, token: null }, ctx.env);
|
|
302
|
+
config.updateProfile(profileName, { workspaceId: null, workspaceName: null }, ctx.env);
|
|
303
|
+
output.success(`已退出登录(profile ${profileName})`, ctx.flags);
|
|
304
|
+
return EXIT.OK;
|
|
305
|
+
},
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
module.exports = {
|
|
309
|
+
id: 'auth',
|
|
310
|
+
summary: '登录 / 状态 / 登出',
|
|
311
|
+
description: '以统一身份(OIDC 授权码 + PKCE)登录平台;CI 场景也可改用 WD_CLI_TOKEN 直连令牌。',
|
|
312
|
+
commands: [login, status, logout],
|
|
313
|
+
fetchLoginConfig,
|
|
314
|
+
};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/** 自动化任务与文件下载短链(/api/open/work/**)。 */
|
|
4
|
+
|
|
5
|
+
const http = require('../http');
|
|
6
|
+
const dataInput = require('../data');
|
|
7
|
+
const output = require('../output');
|
|
8
|
+
const { CliError, EXIT } = output;
|
|
9
|
+
|
|
10
|
+
function requireSessionId(ctx) {
|
|
11
|
+
if (!ctx.flags.sessionId) {
|
|
12
|
+
throw new CliError('缺少 --session-id', EXIT.USAGE, {
|
|
13
|
+
hint: '自动化端点按会话定位发起用户:--session-id <sessionId>',
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
return ctx.flags.sessionId;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const automationTopic = {
|
|
20
|
+
id: 'automation',
|
|
21
|
+
summary: '自动化任务:列出 / 创建',
|
|
22
|
+
principals: ['agent'],
|
|
23
|
+
commands: [
|
|
24
|
+
{
|
|
25
|
+
name: 'list',
|
|
26
|
+
summary: '列出自动化任务',
|
|
27
|
+
flags: { 'session-id': { type: 'string', summary: '会话 id' } },
|
|
28
|
+
examples: ['wd-cli automation list --session-id s-1'],
|
|
29
|
+
async run(ctx) {
|
|
30
|
+
const result = await http.request(ctx, {
|
|
31
|
+
path: '/work/automations',
|
|
32
|
+
query: { sessionId: requireSessionId(ctx) },
|
|
33
|
+
});
|
|
34
|
+
output.print(result, {
|
|
35
|
+
flags: ctx.flags,
|
|
36
|
+
columns: [
|
|
37
|
+
{ key: 'id', label: 'ID' },
|
|
38
|
+
{ key: 'name', label: '名称' },
|
|
39
|
+
{ key: 'cron', label: '触发' },
|
|
40
|
+
{ key: 'status', label: '状态' },
|
|
41
|
+
],
|
|
42
|
+
empty: '还没有自动化任务',
|
|
43
|
+
});
|
|
44
|
+
return EXIT.OK;
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
name: 'create',
|
|
49
|
+
summary: '创建自动化任务',
|
|
50
|
+
flags: {
|
|
51
|
+
'session-id': { type: 'string', summary: '会话 id' },
|
|
52
|
+
data: { type: 'string', summary: '任务体 JSON:内联 / @file / -' },
|
|
53
|
+
},
|
|
54
|
+
examples: ['wd-cli automation create --session-id s-1 --data @task.json'],
|
|
55
|
+
async run(ctx) {
|
|
56
|
+
const body = dataInput.requireJsonData(ctx.flags.data);
|
|
57
|
+
const result = await http.request(ctx, {
|
|
58
|
+
method: 'POST',
|
|
59
|
+
path: '/work/automations',
|
|
60
|
+
query: { sessionId: requireSessionId(ctx) },
|
|
61
|
+
body,
|
|
62
|
+
});
|
|
63
|
+
output.print(result, { flags: ctx.flags });
|
|
64
|
+
output.success('已创建自动化任务', ctx.flags);
|
|
65
|
+
return EXIT.OK;
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
],
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const downloadLinkTopic = {
|
|
72
|
+
id: 'download-link',
|
|
73
|
+
summary: '文件下载短链:签发',
|
|
74
|
+
principals: ['agent'],
|
|
75
|
+
commands: [
|
|
76
|
+
{
|
|
77
|
+
name: 'create',
|
|
78
|
+
summary: '为文件签发下载短链',
|
|
79
|
+
flags: { data: { type: 'string', summary: '请求体 JSON:内联 / @file / -' } },
|
|
80
|
+
examples: ['wd-cli download-link create --data \'{"path":"/data/report.xlsx"}\''],
|
|
81
|
+
async run(ctx) {
|
|
82
|
+
const body = dataInput.requireJsonData(ctx.flags.data);
|
|
83
|
+
const result = await http.request(ctx, { method: 'POST', path: '/work/file-download-links', body });
|
|
84
|
+
output.print(result, { flags: ctx.flags });
|
|
85
|
+
return EXIT.OK;
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
],
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
module.exports = automationTopic;
|
|
92
|
+
module.exports.extraTopics = [downloadLinkTopic];
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Shell 补全(形态对标 gh completion)。脚本从命令表生成:
|
|
5
|
+
* 新增资源组 / 动作后重新 source 一次即可,不必手改补全脚本。
|
|
6
|
+
*
|
|
7
|
+
* bash: eval "$(wd-cli completion bash)" # 或写进 ~/.bashrc
|
|
8
|
+
* zsh: wd-cli completion zsh > "${fpath[1]}/_wd-cli"
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const { GLOBAL_FLAGS } = require('../args');
|
|
12
|
+
const output = require('../output');
|
|
13
|
+
const { CliError, EXIT } = output;
|
|
14
|
+
|
|
15
|
+
function topicWords(registry) {
|
|
16
|
+
return registry.list.map((t) => t.id).join(' ');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** 每个 topic 的动作名(两段式动作取第一段,补全到一级足够用)。 */
|
|
20
|
+
function actionMap(registry) {
|
|
21
|
+
const map = {};
|
|
22
|
+
for (const topic of registry.list) {
|
|
23
|
+
const names = new Set();
|
|
24
|
+
for (const command of topic.commands) {
|
|
25
|
+
if (!command.name) continue;
|
|
26
|
+
names.add(command.name.split(' ')[0]);
|
|
27
|
+
}
|
|
28
|
+
map[topic.id] = [...names];
|
|
29
|
+
}
|
|
30
|
+
return map;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function globalFlagWords() {
|
|
34
|
+
return Object.keys(GLOBAL_FLAGS)
|
|
35
|
+
.map((name) => `--${name}`)
|
|
36
|
+
.join(' ');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function renderBash(registry) {
|
|
40
|
+
const actions = actionMap(registry);
|
|
41
|
+
const caseBranches = Object.entries(actions)
|
|
42
|
+
.map(([topic, names]) => ` ${topic}) actions="${names.join(' ')}" ;;`)
|
|
43
|
+
.join('\n');
|
|
44
|
+
return `# wd-cli bash 补全:eval "$(wd-cli completion bash)"
|
|
45
|
+
_wd_cli_completions() {
|
|
46
|
+
local cur prev topics actions flags
|
|
47
|
+
cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
48
|
+
prev="\${COMP_WORDS[COMP_CWORD-1]}"
|
|
49
|
+
topics="${topicWords(registry)}"
|
|
50
|
+
flags="${globalFlagWords()}"
|
|
51
|
+
|
|
52
|
+
if [ "\$COMP_CWORD" -eq 1 ]; then
|
|
53
|
+
COMPREPLY=( \$(compgen -W "\$topics" -- "\$cur") )
|
|
54
|
+
return 0
|
|
55
|
+
fi
|
|
56
|
+
|
|
57
|
+
case "\${COMP_WORDS[1]}" in
|
|
58
|
+
${caseBranches}
|
|
59
|
+
*) actions="" ;;
|
|
60
|
+
esac
|
|
61
|
+
|
|
62
|
+
if [ "\$COMP_CWORD" -eq 2 ]; then
|
|
63
|
+
COMPREPLY=( \$(compgen -W "\$actions" -- "\$cur") )
|
|
64
|
+
return 0
|
|
65
|
+
fi
|
|
66
|
+
|
|
67
|
+
COMPREPLY=( \$(compgen -W "\$flags" -- "\$cur") )
|
|
68
|
+
return 0
|
|
69
|
+
}
|
|
70
|
+
complete -F _wd_cli_completions wd-cli
|
|
71
|
+
`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function renderZsh(registry) {
|
|
75
|
+
const actions = actionMap(registry);
|
|
76
|
+
const topicLines = registry.list
|
|
77
|
+
.map((topic) => ` '${topic.id}:${topic.summary.replace(/'/g, "")}'`)
|
|
78
|
+
.join('\n');
|
|
79
|
+
const actionCases = Object.entries(actions)
|
|
80
|
+
.map(([topic, names]) => ` ${topic}) _values '动作' ${names.map((n) => `'${n}'`).join(' ')} ;;`)
|
|
81
|
+
.join('\n');
|
|
82
|
+
return `#compdef wd-cli
|
|
83
|
+
# wd-cli zsh 补全:wd-cli completion zsh > "\${fpath[1]}/_wd-cli"
|
|
84
|
+
|
|
85
|
+
_wd_cli() {
|
|
86
|
+
local -a topics
|
|
87
|
+
topics=(
|
|
88
|
+
${topicLines}
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
if (( CURRENT == 2 )); then
|
|
92
|
+
_describe '资源' topics
|
|
93
|
+
return
|
|
94
|
+
fi
|
|
95
|
+
|
|
96
|
+
if (( CURRENT == 3 )); then
|
|
97
|
+
case "\${words[2]}" in
|
|
98
|
+
${actionCases}
|
|
99
|
+
*) ;;
|
|
100
|
+
esac
|
|
101
|
+
return
|
|
102
|
+
fi
|
|
103
|
+
|
|
104
|
+
_values '选项' ${Object.keys(GLOBAL_FLAGS)
|
|
105
|
+
.map((name) => `'--${name}'`)
|
|
106
|
+
.join(' ')}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
_wd_cli "\$@"
|
|
110
|
+
`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const run = {
|
|
114
|
+
name: '',
|
|
115
|
+
summary: '输出 shell 补全脚本',
|
|
116
|
+
args: [{ name: 'shell', required: true, summary: 'bash | zsh' }],
|
|
117
|
+
examples: ['eval "$(wd-cli completion bash)"', 'wd-cli completion zsh > "${fpath[1]}/_wd-cli"'],
|
|
118
|
+
skipPrincipalCheck: true,
|
|
119
|
+
workspaceOptional: true,
|
|
120
|
+
async run(ctx) {
|
|
121
|
+
const shell = String(ctx.args[0]).toLowerCase();
|
|
122
|
+
if (shell === 'bash') {
|
|
123
|
+
process.stdout.write(renderBash(ctx.registry));
|
|
124
|
+
return EXIT.OK;
|
|
125
|
+
}
|
|
126
|
+
if (shell === 'zsh') {
|
|
127
|
+
process.stdout.write(renderZsh(ctx.registry));
|
|
128
|
+
return EXIT.OK;
|
|
129
|
+
}
|
|
130
|
+
throw new CliError(`暂不支持的 shell:${shell}`, EXIT.USAGE, { hint: '当前支持 bash 与 zsh' });
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
module.exports = {
|
|
135
|
+
id: 'completion',
|
|
136
|
+
summary: '生成 shell 补全脚本',
|
|
137
|
+
commands: [run],
|
|
138
|
+
renderBash,
|
|
139
|
+
renderZsh,
|
|
140
|
+
actionMap,
|
|
141
|
+
};
|