@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.
@@ -0,0 +1,385 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 应用(Agent)信息与对话。
5
+ *
6
+ * 对话走 POST /api/open/{agentCode}/chat,两种模式:
7
+ * block 一次拿全量回复
8
+ * stream 消费 AG-UI 事件流,文本增量即时打到标准输出
9
+ *
10
+ * 对话端点在 server/gateway 进程;网关把两类 /api/open 收在同一域名时无需额外配置,
11
+ * 拆开部署则用 profile 的 chatBaseUrl 指过去。
12
+ */
13
+
14
+ const readline = require('node:readline');
15
+
16
+ const http = require('../http');
17
+ const dataInput = require('../data');
18
+ const output = require('../output');
19
+ const { CliError, EXIT } = output;
20
+
21
+ /** AG-UI 文本增量事件的几种命名(跨版本兼容),命中即取其文本。 */
22
+ function extractDelta(payload) {
23
+ if (!payload || typeof payload !== 'object') return null;
24
+ const type = String(payload.type || payload.event || '');
25
+ if (/TEXT_MESSAGE_CONTENT|TEXT_MESSAGE_DELTA|delta/i.test(type)) {
26
+ return payload.delta ?? payload.content ?? payload.text ?? null;
27
+ }
28
+ if (payload.delta !== undefined && typeof payload.delta === 'string') return payload.delta;
29
+ return null;
30
+ }
31
+
32
+ function isFinished(payload) {
33
+ const type = String((payload && (payload.type || payload.event)) || '');
34
+ return /RUN_FINISHED|done|finish/i.test(type);
35
+ }
36
+
37
+ const AGENT_COLUMNS = [
38
+ { key: 'agentCode', label: 'ID' },
39
+ { key: 'name', label: '名称' },
40
+ { key: 'appType', label: '类型' },
41
+ { key: 'status', label: '状态' },
42
+ { key: 'latestVersion', label: '版本' },
43
+ { key: 'updatedAt', label: '更新时间' },
44
+ ];
45
+
46
+ const list = {
47
+ name: 'list',
48
+ summary: '列出当前工作空间的应用',
49
+ flags: {
50
+ q: { type: 'string', summary: '按名称 / 描述过滤' },
51
+ type: { type: 'string', summary: '按应用类型过滤' },
52
+ published: { type: 'boolean', summary: '只看已发布的(可以对话的)' },
53
+ page: { type: 'number', summary: '页码' },
54
+ 'page-size': { type: 'number', summary: '每页条数(上限 100)' },
55
+ paginate: { type: 'boolean', summary: '自动翻页取全部' },
56
+ },
57
+ examples: [
58
+ 'wd-cli agent list',
59
+ 'wd-cli agent list --q 客服 --published',
60
+ 'wd-cli agent list --paginate --json agentCode,name',
61
+ ],
62
+ // 列整个空间的应用:工作空间令牌或登录态可用,应用访问密钥只代表单个应用
63
+ principals: ['workspace'],
64
+ async run(ctx) {
65
+ const options = {
66
+ path: '/workspace-agents',
67
+ query: {
68
+ q: ctx.flags.q,
69
+ appType: ctx.flags.type,
70
+ publishedOnly: ctx.flags.published ? 'true' : undefined,
71
+ pageNum: ctx.flags.page,
72
+ pageSize: ctx.flags.pageSize,
73
+ },
74
+ };
75
+ const result = ctx.flags.paginate ? await http.requestAllPages(ctx, options) : await http.request(ctx, options);
76
+ const rows = Array.isArray(result) ? result : result && result.list ? result.list : result;
77
+ output.print(rows, {
78
+ flags: ctx.flags,
79
+ columns: AGENT_COLUMNS,
80
+ empty: ctx.flags.q || ctx.flags.type || ctx.flags.published ? '没有符合条件的应用' : '当前工作空间还没有应用',
81
+ });
82
+ return EXIT.OK;
83
+ },
84
+ };
85
+
86
+ /**
87
+ * 建一个新会话并返回服务端生成的 sessionId。
88
+ *
89
+ * work 要求 sessionId 已落 agent_chat_session(凭证解引用与归属校验都按它反解),
90
+ * 客户端自己编一个 id 发过去必然 404,所以没指定会话时一律先建。
91
+ * 会话 id 由服务端生成,端点不接受客户端指定。
92
+ */
93
+ async function createSession(ctx, agentCode) {
94
+ const created = await http.request(ctx, {
95
+ method: 'POST',
96
+ base: ctx.chatBase(),
97
+ path: `/${encodeURIComponent(agentCode)}/newsession`,
98
+ });
99
+ const sessionId = created && created.sessionId;
100
+ if (!sessionId) {
101
+ throw new CliError('建会话失败:服务端未返回 sessionId', EXIT.BUSINESS);
102
+ }
103
+ return sessionId;
104
+ }
105
+
106
+ /** 指定的会话不存在时,把 404 换成能照着做的指引。 */
107
+ function explainMissingSession(error, sessionId) {
108
+ if (!sessionId || !(error instanceof CliError)) return error;
109
+ // body 带 code 时取 code;兜底分支只有 HTTP 状态进消息文本,一并认
110
+ const notFound = error.code === 404 || /HTTP 404|session not found/i.test(error.message || '');
111
+ if (!notFound) return error;
112
+ return new CliError(`会话不存在:${sessionId}`, EXIT.BUSINESS, {
113
+ code: 404,
114
+ hint: '去掉 --session-id 让 wd-cli 自动新建;已有会话可用 wd-cli session list <agentCode> 查看',
115
+ });
116
+ }
117
+
118
+ function errorMessage(payload) {
119
+ const type = String((payload && (payload.type || payload.event)) || '');
120
+ if (!/RUN_ERROR|error/i.test(type)) return null;
121
+ return (payload && (payload.message || payload.error || payload.detail)) || '运行失败';
122
+ }
123
+
124
+ const info = {
125
+ name: 'info',
126
+ summary: '查看当前凭据对应的应用信息',
127
+ flags: { 'agent-code': { type: 'string', summary: '应用标识(登录态下必填)' } },
128
+ examples: ['wd-cli agent info --agent-code 66'],
129
+ async run(ctx) {
130
+ const result = await http.request(ctx, { path: '/agent', query: { agentCode: ctx.flags.agentCode } });
131
+ output.print(result, { flags: ctx.flags });
132
+ return EXIT.OK;
133
+ },
134
+ };
135
+
136
+ const metadata = {
137
+ name: 'metadata',
138
+ summary: '查看应用编排元数据',
139
+ args: [{ name: 'agentCode', required: true, summary: '应用标识(agentId 或 agentId#versionId)' }],
140
+ examples: ['wd-cli agent metadata 66'],
141
+ async run(ctx) {
142
+ const code = encodeURIComponent(ctx.args[0]);
143
+ const result = await http.request(ctx, {
144
+ path: `/agents/${code}/metadata`,
145
+ query: { agentCode: ctx.args[0] },
146
+ });
147
+ output.print(result, { flags: ctx.flags });
148
+ return EXIT.OK;
149
+ },
150
+ };
151
+
152
+ const revision = {
153
+ name: 'revision',
154
+ summary: '查看应用编排版本号',
155
+ args: [{ name: 'agentCode', required: true, summary: '应用标识' }],
156
+ examples: ['wd-cli agent revision 66'],
157
+ async run(ctx) {
158
+ const code = encodeURIComponent(ctx.args[0]);
159
+ const result = await http.request(ctx, {
160
+ path: `/agents/${code}/revision`,
161
+ query: { agentCode: ctx.args[0] },
162
+ });
163
+ output.print(result, { flags: ctx.flags });
164
+ return EXIT.OK;
165
+ },
166
+ };
167
+
168
+ const model = {
169
+ name: 'model',
170
+ summary: '查看模型配置',
171
+ args: [{ name: 'modelId', required: true, summary: '模型 id' }],
172
+ flags: { 'agent-code': { type: 'string', summary: '应用标识(登录态下必填)' } },
173
+ examples: ['wd-cli agent model 3 --agent-code 66'],
174
+ async run(ctx) {
175
+ const result = await http.request(ctx, {
176
+ path: `/llm-models/${encodeURIComponent(ctx.args[0])}`,
177
+ query: { agentCode: ctx.flags.agentCode },
178
+ });
179
+ output.print(result, { flags: ctx.flags });
180
+ return EXIT.OK;
181
+ },
182
+ };
183
+
184
+ /**
185
+ * 发一轮对话,回复写标准输出。单次与连续对话共用这一条路径。
186
+ * 出错一律抛 CliError:单次模式直接决定退出码,连续对话里由调用方接住、只报一轮失败。
187
+ */
188
+ async function sendTurn(ctx, { agentCode, sessionId, message, stream, asJson, declaredSessionId }) {
189
+ const path = `/${encodeURIComponent(agentCode)}/chat`;
190
+ const onError = (error) => {
191
+ throw explainMissingSession(error, declaredSessionId);
192
+ };
193
+
194
+ if (!stream) {
195
+ const result = await http
196
+ .request(ctx, {
197
+ method: 'POST',
198
+ base: ctx.chatBase(),
199
+ path,
200
+ body: { sessionId, message, mode: 'block' },
201
+ })
202
+ .catch(onError);
203
+ const text =
204
+ result && typeof result === 'object'
205
+ ? result.reply ?? result.message ?? result.content ?? JSON.stringify(result)
206
+ : result;
207
+ output.print(text, { flags: ctx.flags });
208
+ return;
209
+ }
210
+
211
+ let failure = null;
212
+ let wroteAny = false;
213
+ await http
214
+ .stream(ctx, {
215
+ method: 'POST',
216
+ base: ctx.chatBase(),
217
+ path,
218
+ body: { sessionId, message, mode: 'stream' },
219
+ onEvent: ({ data }) => {
220
+ if (asJson) {
221
+ process.stdout.write(`${typeof data === 'string' ? data : JSON.stringify(data)}\n`);
222
+ return;
223
+ }
224
+ const error = errorMessage(data);
225
+ if (error) {
226
+ failure = error;
227
+ return;
228
+ }
229
+ const delta = extractDelta(data);
230
+ if (delta) {
231
+ process.stdout.write(String(delta));
232
+ wroteAny = true;
233
+ }
234
+ },
235
+ })
236
+ .catch(onError);
237
+ if (!asJson && wroteAny) process.stdout.write('\n');
238
+ if (failure) throw new CliError(failure, EXIT.BUSINESS);
239
+ }
240
+
241
+ /** 连续对话里可用的斜杠命令,供提示与补全。 */
242
+ const REPL_COMMANDS = ['/exit', '/quit', '/new', '/session', '/help'];
243
+
244
+ function printReplHelp(ctx) {
245
+ output.info(' /new 换一个新会话(清空上下文)', ctx.flags);
246
+ output.info(' /session 显示当前会话 id', ctx.flags);
247
+ output.info(' /exit 退出(Ctrl-D 同效)', ctx.flags);
248
+ }
249
+
250
+ /**
251
+ * 连续对话:同一个会话反复发问,上下文由服务端按 sessionId 维持。
252
+ *
253
+ * 提示符与所有提示走标准错误,回复走标准输出——这样 `wd-cli agent chat 66 > out.txt`
254
+ * 仍只把回复落进文件(clig.dev)。Ctrl-D(EOF)与 /exit 都能正常收尾。
255
+ */
256
+ async function runInteractive(ctx, { agentCode, sessionId, stream, asJson }) {
257
+ const rl = readline.createInterface({
258
+ input: process.stdin,
259
+ output: process.stderr,
260
+ prompt: '> ',
261
+ completer: (line) => {
262
+ const hits = REPL_COMMANDS.filter((c) => c.startsWith(line));
263
+ return [hits.length ? hits : REPL_COMMANDS, line];
264
+ },
265
+ });
266
+ // Ctrl-C 结束当前 REPL,而不是让 readline 默认继续等输入
267
+ rl.on('SIGINT', () => rl.close());
268
+
269
+ output.info('连续对话已开始,/help 看可用命令,/exit 或 Ctrl-D 退出。', ctx.flags);
270
+ let current = sessionId;
271
+ rl.prompt();
272
+ for await (const raw of rl) {
273
+ const line = String(raw).trim();
274
+ if (!line) {
275
+ rl.prompt();
276
+ continue;
277
+ }
278
+ if (line === '/exit' || line === '/quit') break;
279
+ if (line === '/help') {
280
+ printReplHelp(ctx);
281
+ rl.prompt();
282
+ continue;
283
+ }
284
+ if (line === '/session') {
285
+ output.info(`当前会话:${current}`, ctx.flags);
286
+ rl.prompt();
287
+ continue;
288
+ }
289
+ if (line === '/new') {
290
+ try {
291
+ current = await createSession(ctx, agentCode);
292
+ output.info(`已切到新会话:${current}`, ctx.flags);
293
+ } catch (error) {
294
+ output.warn(`建会话失败:${error.message}`, ctx.flags);
295
+ }
296
+ rl.prompt();
297
+ continue;
298
+ }
299
+ try {
300
+ // 会话是这里建/接手的,一轮失败不该把整个对话带走,故不传 declaredSessionId
301
+ await sendTurn(ctx, { agentCode, sessionId: current, message: line, stream, asJson });
302
+ } catch (error) {
303
+ output.warn(error.message, ctx.flags);
304
+ }
305
+ rl.prompt();
306
+ }
307
+ rl.close();
308
+ output.info(`对话结束。下次接着聊:wd-cli agent chat ${agentCode} --session-id ${current}`, ctx.flags);
309
+ }
310
+
311
+ const chat = {
312
+ name: 'chat',
313
+ summary: '与应用对话(单次、连续对话、阻塞或流式)',
314
+ args: [{ name: 'agentCode', required: true, summary: '应用标识' }],
315
+ flags: {
316
+ message: { type: 'string', short: 'm', summary: '消息内容;- 表示从标准输入读。不给则进入连续对话' },
317
+ 'session-id': { type: 'string', summary: '接着已有会话聊;缺省自动新建一个并在标准错误提示 id' },
318
+ stream: { type: 'boolean', summary: '流式输出(消费 AG-UI 事件)' },
319
+ interactive: { type: 'boolean', short: 'i', summary: '发完 --message 后继续连续对话' },
320
+ },
321
+ examples: [
322
+ 'wd-cli agent chat 66',
323
+ 'wd-cli agent chat 66 -m "你好"',
324
+ 'wd-cli agent chat 66 -m "写一段介绍" --stream',
325
+ 'wd-cli agent chat 66 -i --stream',
326
+ 'cat prompt.txt | wd-cli agent chat 66 -m - --session-id s1',
327
+ ],
328
+ async run(ctx) {
329
+ const agentCode = ctx.args[0];
330
+ const messageRaw = ctx.flags.message;
331
+ const stream = Boolean(ctx.flags.stream);
332
+ const asJson = ctx.flags.output === 'json' || ctx.flags.json || ctx.flags.jq;
333
+
334
+ // 不给 --message 就进连续对话;但标准输入不是终端时(脚本 / 管道)保持报错,
335
+ // 免得 CI 里漏传 -m 的命令挂在那儿等输入。
336
+ const interactive = Boolean(ctx.flags.interactive) || messageRaw === undefined;
337
+ if (messageRaw === undefined && !process.stdin.isTTY) {
338
+ throw new CliError('缺少 --message', EXIT.USAGE, {
339
+ hint: '例:wd-cli agent chat 66 -m "你好";也可 -m - 从标准输入读;终端里不加 -m 即进入连续对话',
340
+ });
341
+ }
342
+
343
+ // 没指定会话就先建一个:服务端按落库行校验 sessionId,自造的 id 一律 404
344
+ const sessionId = ctx.flags.sessionId || (await createSession(ctx, agentCode));
345
+ if (!ctx.flags.sessionId) {
346
+ output.info(`会话 id:${sessionId}(下次加 --session-id ${sessionId} 可接着聊)`, ctx.flags);
347
+ }
348
+
349
+ if (messageRaw !== undefined) {
350
+ const message = String(dataInput.readDataText(messageRaw, '--message')).trim();
351
+ if (!message) throw new CliError('消息内容为空', EXIT.USAGE);
352
+ try {
353
+ await sendTurn(ctx, {
354
+ agentCode,
355
+ sessionId,
356
+ message,
357
+ stream,
358
+ asJson,
359
+ declaredSessionId: ctx.flags.sessionId,
360
+ });
361
+ } catch (error) {
362
+ // 单次模式下这一轮就是全部,错误直接决定退出码;
363
+ // 要继续聊的话,首轮失败不该把后面的机会一起收走
364
+ if (!interactive) throw error;
365
+ output.warn(error.message, ctx.flags);
366
+ }
367
+ }
368
+
369
+ if (interactive) {
370
+ await runInteractive(ctx, { agentCode, sessionId, stream, asJson });
371
+ }
372
+ return EXIT.OK;
373
+ },
374
+ };
375
+
376
+ module.exports = {
377
+ id: 'agent',
378
+ summary: '应用:列表 / 信息 / 元数据 / 对话',
379
+ description: '对话端点在 server/gateway;与其余 Open API 不同域名时用 wd-cli config set chatBaseUrl 指定。',
380
+ principals: ['agent'],
381
+ commands: [list, info, metadata, revision, model, chat],
382
+ extractDelta,
383
+ isFinished,
384
+ errorMessage,
385
+ };
@@ -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
+ };