@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,784 @@
|
|
|
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 fs = require('node:fs');
|
|
15
|
+
const readline = require('node:readline');
|
|
16
|
+
|
|
17
|
+
const http = require('../http');
|
|
18
|
+
const dataInput = require('../data');
|
|
19
|
+
const output = require('../output');
|
|
20
|
+
const { CliError, EXIT } = output;
|
|
21
|
+
|
|
22
|
+
/** AG-UI 文本增量事件的几种命名(跨版本兼容),命中即取其文本。 */
|
|
23
|
+
function extractDelta(payload) {
|
|
24
|
+
if (!payload || typeof payload !== 'object') return null;
|
|
25
|
+
const type = String(payload.type || payload.event || '');
|
|
26
|
+
if (/TEXT_MESSAGE_CONTENT|TEXT_MESSAGE_DELTA|delta/i.test(type)) {
|
|
27
|
+
return payload.delta ?? payload.content ?? payload.text ?? null;
|
|
28
|
+
}
|
|
29
|
+
if (payload.delta !== undefined && typeof payload.delta === 'string') return payload.delta;
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function isFinished(payload) {
|
|
34
|
+
const type = String((payload && (payload.type || payload.event)) || '');
|
|
35
|
+
return /RUN_FINISHED|done|finish/i.test(type);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function extractTraceId(payload, headers) {
|
|
39
|
+
if (headers) {
|
|
40
|
+
const fromHeader = typeof headers.get === 'function' ? headers.get('x-trace-id') : headers['x-trace-id'];
|
|
41
|
+
if (fromHeader && String(fromHeader).trim() !== '00000000000000000000000000000000') {
|
|
42
|
+
return String(fromHeader).trim();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (!payload || typeof payload !== 'object') return null;
|
|
46
|
+
const tid =
|
|
47
|
+
payload.traceId ||
|
|
48
|
+
payload.trace_id ||
|
|
49
|
+
(payload.metadata && (payload.metadata.traceId || payload.metadata.trace_id)) ||
|
|
50
|
+
(payload.data && (payload.data.traceId || payload.data.trace_id)) ||
|
|
51
|
+
null;
|
|
52
|
+
if (tid && String(tid).trim() !== '00000000000000000000000000000000') {
|
|
53
|
+
return String(tid).trim();
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const AGENT_COLUMNS = [
|
|
59
|
+
{ key: 'agentCode', label: 'ID' },
|
|
60
|
+
{ key: 'name', label: '名称' },
|
|
61
|
+
{ key: 'appType', label: '类型' },
|
|
62
|
+
{ key: 'status', label: '状态' },
|
|
63
|
+
{ key: 'latestVersion', label: '版本' },
|
|
64
|
+
{ key: 'updatedAt', label: '更新时间' },
|
|
65
|
+
];
|
|
66
|
+
|
|
67
|
+
const list = {
|
|
68
|
+
name: 'list',
|
|
69
|
+
summary: '列出当前工作空间的应用',
|
|
70
|
+
flags: {
|
|
71
|
+
q: { type: 'string', summary: '按名称 / 描述过滤' },
|
|
72
|
+
type: { type: 'string', summary: '按应用类型过滤' },
|
|
73
|
+
published: { type: 'boolean', summary: '只看已发布的(可以对话的)' },
|
|
74
|
+
page: { type: 'number', summary: '页码' },
|
|
75
|
+
'page-size': { type: 'number', summary: '每页条数(上限 100)' },
|
|
76
|
+
paginate: { type: 'boolean', summary: '自动翻页取全部' },
|
|
77
|
+
},
|
|
78
|
+
examples: [
|
|
79
|
+
'wd-cli agent list',
|
|
80
|
+
'wd-cli agent list --q 客服 --published',
|
|
81
|
+
'wd-cli agent list --paginate --json agentCode,name',
|
|
82
|
+
],
|
|
83
|
+
// 列整个空间的应用:工作空间令牌或登录态可用,应用访问密钥只代表单个应用
|
|
84
|
+
principals: ['workspace'],
|
|
85
|
+
async run(ctx) {
|
|
86
|
+
const options = {
|
|
87
|
+
path: '/workspace-agents',
|
|
88
|
+
query: {
|
|
89
|
+
q: ctx.flags.q,
|
|
90
|
+
appType: ctx.flags.type,
|
|
91
|
+
publishedOnly: ctx.flags.published ? 'true' : undefined,
|
|
92
|
+
pageNum: ctx.flags.page,
|
|
93
|
+
pageSize: ctx.flags.pageSize,
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
const result = ctx.flags.paginate ? await http.requestAllPages(ctx, options) : await http.request(ctx, options);
|
|
97
|
+
const rows = Array.isArray(result) ? result : result && result.list ? result.list : result;
|
|
98
|
+
output.print(rows, {
|
|
99
|
+
flags: ctx.flags,
|
|
100
|
+
columns: AGENT_COLUMNS,
|
|
101
|
+
empty: ctx.flags.q || ctx.flags.type || ctx.flags.published ? '没有符合条件的应用' : '当前工作空间还没有应用',
|
|
102
|
+
});
|
|
103
|
+
return EXIT.OK;
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 建一个新会话并返回服务端生成的 sessionId。
|
|
109
|
+
*
|
|
110
|
+
* work 要求 sessionId 已落 agent_chat_session(凭证解引用与归属校验都按它反解),
|
|
111
|
+
* 客户端自己编一个 id 发过去必然 404,所以没指定会话时一律先建。
|
|
112
|
+
* 会话 id 由服务端生成,端点不接受客户端指定。
|
|
113
|
+
*/
|
|
114
|
+
async function createSession(ctx, agentCode) {
|
|
115
|
+
const created = await http.request(ctx, {
|
|
116
|
+
method: 'POST',
|
|
117
|
+
base: ctx.chatBase(),
|
|
118
|
+
path: `/${encodeURIComponent(agentCode)}/newsession`,
|
|
119
|
+
});
|
|
120
|
+
const sessionId = created && created.sessionId;
|
|
121
|
+
if (!sessionId) {
|
|
122
|
+
throw new CliError('建会话失败:服务端未返回 sessionId', EXIT.BUSINESS);
|
|
123
|
+
}
|
|
124
|
+
return sessionId;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** 指定的会话不存在时,把 404 换成能照着做的指引。 */
|
|
128
|
+
function explainMissingSession(error, sessionId) {
|
|
129
|
+
if (!sessionId || !(error instanceof CliError)) return error;
|
|
130
|
+
// body 带 code 时取 code;兜底分支只有 HTTP 状态进消息文本,一并认
|
|
131
|
+
const notFound = error.code === 404 || /HTTP 404|session not found/i.test(error.message || '');
|
|
132
|
+
if (!notFound) return error;
|
|
133
|
+
return new CliError(`会话不存在:${sessionId}`, EXIT.BUSINESS, {
|
|
134
|
+
code: 404,
|
|
135
|
+
hint: '去掉 --session-id 让 wd-cli 自动新建;已有会话可用 wd-cli session list <agentCode> 查看',
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function errorMessage(payload) {
|
|
140
|
+
const type = String((payload && (payload.type || payload.event)) || '');
|
|
141
|
+
if (!/RUN_ERROR|error/i.test(type)) return null;
|
|
142
|
+
return (payload && (payload.message || payload.error || payload.detail)) || '运行失败';
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const info = {
|
|
146
|
+
name: 'info',
|
|
147
|
+
summary: '查看当前凭据对应的应用信息',
|
|
148
|
+
flags: { 'agent-code': { type: 'string', summary: '应用标识(登录态下必填)' } },
|
|
149
|
+
examples: ['wd-cli agent info --agent-code 66'],
|
|
150
|
+
async run(ctx) {
|
|
151
|
+
const result = await http.request(ctx, { path: '/agent', query: { agentCode: ctx.flags.agentCode } });
|
|
152
|
+
output.print(result, { flags: ctx.flags });
|
|
153
|
+
return EXIT.OK;
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
const metadata = {
|
|
158
|
+
name: 'metadata',
|
|
159
|
+
summary: '查看应用编排元数据',
|
|
160
|
+
args: [{ name: 'agentCode', required: true, summary: '应用标识(agentId 或 agentId#versionId)' }],
|
|
161
|
+
examples: ['wd-cli agent metadata 66'],
|
|
162
|
+
async run(ctx) {
|
|
163
|
+
const code = encodeURIComponent(ctx.args[0]);
|
|
164
|
+
const result = await http.request(ctx, {
|
|
165
|
+
path: `/agents/${code}/metadata`,
|
|
166
|
+
query: { agentCode: ctx.args[0] },
|
|
167
|
+
});
|
|
168
|
+
output.print(result, { flags: ctx.flags });
|
|
169
|
+
return EXIT.OK;
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const revision = {
|
|
174
|
+
name: 'revision',
|
|
175
|
+
summary: '查看应用编排版本号',
|
|
176
|
+
args: [{ name: 'agentCode', required: true, summary: '应用标识' }],
|
|
177
|
+
examples: ['wd-cli agent revision 66'],
|
|
178
|
+
async run(ctx) {
|
|
179
|
+
const code = encodeURIComponent(ctx.args[0]);
|
|
180
|
+
const result = await http.request(ctx, {
|
|
181
|
+
path: `/agents/${code}/revision`,
|
|
182
|
+
query: { agentCode: ctx.args[0] },
|
|
183
|
+
});
|
|
184
|
+
output.print(result, { flags: ctx.flags });
|
|
185
|
+
return EXIT.OK;
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
const model = {
|
|
190
|
+
name: 'model',
|
|
191
|
+
summary: '查看模型配置',
|
|
192
|
+
args: [{ name: 'modelId', required: true, summary: '模型 id' }],
|
|
193
|
+
flags: { 'agent-code': { type: 'string', summary: '应用标识(登录态下必填)' } },
|
|
194
|
+
examples: ['wd-cli agent model 3 --agent-code 66'],
|
|
195
|
+
async run(ctx) {
|
|
196
|
+
const result = await http.request(ctx, {
|
|
197
|
+
path: `/llm-models/${encodeURIComponent(ctx.args[0])}`,
|
|
198
|
+
query: { agentCode: ctx.flags.agentCode },
|
|
199
|
+
});
|
|
200
|
+
output.print(result, { flags: ctx.flags });
|
|
201
|
+
return EXIT.OK;
|
|
202
|
+
},
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* 发一轮对话,回复写标准输出。单次与连续对话共用这一条路径。
|
|
207
|
+
* 出错一律抛 CliError:单次模式直接决定退出码,连续对话里由调用方接住、只报一轮失败。
|
|
208
|
+
*/
|
|
209
|
+
async function sendTurn(ctx, { agentCode, sessionId, message, stream, asJson, declaredSessionId, withTrace, traceOnly }) {
|
|
210
|
+
const path = `/${encodeURIComponent(agentCode)}/chat`;
|
|
211
|
+
const onError = (error) => {
|
|
212
|
+
throw explainMissingSession(error, declaredSessionId);
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
let traceId = null;
|
|
216
|
+
|
|
217
|
+
if (!stream) {
|
|
218
|
+
const result = await http
|
|
219
|
+
.request(ctx, {
|
|
220
|
+
method: 'POST',
|
|
221
|
+
base: ctx.chatBase(),
|
|
222
|
+
path,
|
|
223
|
+
body: { sessionId, message, mode: 'block' },
|
|
224
|
+
onResponse: (res) => {
|
|
225
|
+
const tid = extractTraceId(null, res.headers);
|
|
226
|
+
if (tid) traceId = tid;
|
|
227
|
+
},
|
|
228
|
+
})
|
|
229
|
+
.catch(onError);
|
|
230
|
+
|
|
231
|
+
if (!traceId) {
|
|
232
|
+
traceId = extractTraceId(result);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
if (traceOnly) {
|
|
236
|
+
process.stdout.write(`${traceId || ''}\n`);
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const text =
|
|
241
|
+
result && typeof result === 'object'
|
|
242
|
+
? result.reply ?? result.message ?? result.content ?? JSON.stringify(result)
|
|
243
|
+
: result;
|
|
244
|
+
|
|
245
|
+
if (asJson) {
|
|
246
|
+
output.print({ reply: text, sessionId, traceId: traceId || null }, { flags: ctx.flags });
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
output.print(text, { flags: ctx.flags });
|
|
251
|
+
if (withTrace && traceId) {
|
|
252
|
+
process.stdout.write(`[TraceId: ${traceId}]\n`);
|
|
253
|
+
}
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
let failure = null;
|
|
258
|
+
let wroteAny = false;
|
|
259
|
+
let replyText = '';
|
|
260
|
+
await http
|
|
261
|
+
.stream(ctx, {
|
|
262
|
+
method: 'POST',
|
|
263
|
+
base: ctx.chatBase(),
|
|
264
|
+
path,
|
|
265
|
+
body: { sessionId, message, mode: 'stream' },
|
|
266
|
+
onResponse: (res) => {
|
|
267
|
+
const tid = extractTraceId(null, res.headers);
|
|
268
|
+
if (tid) traceId = tid;
|
|
269
|
+
},
|
|
270
|
+
onEvent: ({ data }) => {
|
|
271
|
+
const tid = extractTraceId(data);
|
|
272
|
+
if (tid) traceId = tid;
|
|
273
|
+
|
|
274
|
+
const error = errorMessage(data);
|
|
275
|
+
if (error) {
|
|
276
|
+
failure = error;
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
const delta = extractDelta(data);
|
|
280
|
+
if (delta) {
|
|
281
|
+
replyText += String(delta);
|
|
282
|
+
if (!asJson && !traceOnly) {
|
|
283
|
+
process.stdout.write(String(delta));
|
|
284
|
+
wroteAny = true;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
},
|
|
288
|
+
})
|
|
289
|
+
.catch(onError);
|
|
290
|
+
|
|
291
|
+
if (failure) throw new CliError(failure, EXIT.BUSINESS);
|
|
292
|
+
|
|
293
|
+
if (traceOnly) {
|
|
294
|
+
process.stdout.write(`${traceId || ''}\n`);
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
if (asJson) {
|
|
299
|
+
output.print({ reply: replyText, sessionId, traceId: traceId || null }, { flags: ctx.flags });
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
if (wroteAny) process.stdout.write('\n');
|
|
304
|
+
if (withTrace && traceId) {
|
|
305
|
+
process.stdout.write(`[TraceId: ${traceId}]\n`);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** 连续对话里可用的斜杠命令,供提示与补全。 */
|
|
310
|
+
const REPL_COMMANDS = ['/exit', '/quit', '/new', '/session', '/help'];
|
|
311
|
+
|
|
312
|
+
function printReplHelp(ctx) {
|
|
313
|
+
output.info(' /new 换一个新会话(清空上下文)', ctx.flags);
|
|
314
|
+
output.info(' /session 显示当前会话 id', ctx.flags);
|
|
315
|
+
output.info(' /exit 退出(Ctrl-D 同效)', ctx.flags);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* 连续对话:同一个会话反复发问,上下文由服务端按 sessionId 维持。
|
|
320
|
+
*
|
|
321
|
+
* 提示符与所有提示走标准错误,回复走标准输出——这样 `wd-cli agent chat 66 > out.txt`
|
|
322
|
+
* 仍只把回复落进文件(clig.dev)。Ctrl-D(EOF)与 /exit 都能正常收尾。
|
|
323
|
+
*/
|
|
324
|
+
async function runInteractive(ctx, { agentCode, sessionId, stream, asJson, withTrace, traceOnly }) {
|
|
325
|
+
const rl = readline.createInterface({
|
|
326
|
+
input: process.stdin,
|
|
327
|
+
output: process.stderr,
|
|
328
|
+
prompt: '> ',
|
|
329
|
+
completer: (line) => {
|
|
330
|
+
const hits = REPL_COMMANDS.filter((c) => c.startsWith(line));
|
|
331
|
+
return [hits.length ? hits : REPL_COMMANDS, line];
|
|
332
|
+
},
|
|
333
|
+
});
|
|
334
|
+
// Ctrl-C 结束当前 REPL,而不是让 readline 默认继续等输入
|
|
335
|
+
rl.on('SIGINT', () => rl.close());
|
|
336
|
+
|
|
337
|
+
function safePrompt() {
|
|
338
|
+
try {
|
|
339
|
+
if (!rl.closed) rl.prompt();
|
|
340
|
+
} catch {}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
output.info('连续对话已开始,/help 看可用命令,/exit 或 Ctrl-D 退出。', ctx.flags);
|
|
344
|
+
let current = sessionId;
|
|
345
|
+
safePrompt();
|
|
346
|
+
for await (const raw of rl) {
|
|
347
|
+
const line = String(raw).trim();
|
|
348
|
+
if (!line) {
|
|
349
|
+
safePrompt();
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
if (line === '/exit' || line === '/quit') break;
|
|
353
|
+
if (line === '/help') {
|
|
354
|
+
printReplHelp(ctx);
|
|
355
|
+
safePrompt();
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
if (line === '/session') {
|
|
359
|
+
output.info(`当前会话:${current}`, ctx.flags);
|
|
360
|
+
safePrompt();
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
if (line === '/new') {
|
|
364
|
+
try {
|
|
365
|
+
current = await createSession(ctx, agentCode);
|
|
366
|
+
output.info(`已切到新会话:${current}`, ctx.flags);
|
|
367
|
+
} catch (error) {
|
|
368
|
+
output.warn(`建会话失败:${error.message}`, ctx.flags);
|
|
369
|
+
}
|
|
370
|
+
safePrompt();
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
try {
|
|
374
|
+
// 会话是这里建/接手的,一轮失败不该把整个对话带走,故不传 declaredSessionId
|
|
375
|
+
await sendTurn(ctx, { agentCode, sessionId: current, message: line, stream, asJson, withTrace, traceOnly });
|
|
376
|
+
} catch (error) {
|
|
377
|
+
output.warn(error.message, ctx.flags);
|
|
378
|
+
}
|
|
379
|
+
safePrompt();
|
|
380
|
+
}
|
|
381
|
+
try {
|
|
382
|
+
if (!rl.closed) rl.close();
|
|
383
|
+
} catch {}
|
|
384
|
+
output.info(`对话结束。下次接着聊:wd-cli agent chat ${agentCode} --session-id ${current}`, ctx.flags);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const chat = {
|
|
388
|
+
name: 'chat',
|
|
389
|
+
summary: '与应用对话(单次、连续对话、阻塞或流式)',
|
|
390
|
+
args: [{ name: 'agentCode', required: true, summary: '应用标识' }],
|
|
391
|
+
flags: {
|
|
392
|
+
message: { type: 'string', short: 'm', summary: '消息内容;- 表示从标准输入读。不给则进入连续对话' },
|
|
393
|
+
'session-id': { type: 'string', summary: '接着已有会话聊;缺省自动新建一个并在标准错误提示 id' },
|
|
394
|
+
stream: { type: 'boolean', summary: '流式输出(消费 AG-UI 事件)' },
|
|
395
|
+
interactive: { type: 'boolean', short: 'i', summary: '发完 --message 后继续连续对话' },
|
|
396
|
+
'with-trace': { type: 'boolean', summary: '输出中附带本次会话关联的 traceId' },
|
|
397
|
+
'trace-only': { type: 'boolean', summary: '仅输出 traceId' },
|
|
398
|
+
},
|
|
399
|
+
examples: [
|
|
400
|
+
'wd-cli agent chat 66',
|
|
401
|
+
'wd-cli agent chat 66 -m "你好"',
|
|
402
|
+
'wd-cli agent chat 66 -m "写一段介绍" --stream',
|
|
403
|
+
'wd-cli agent chat 66 -i --stream',
|
|
404
|
+
'cat prompt.txt | wd-cli agent chat 66 -m - --session-id s1',
|
|
405
|
+
'wd-cli agent chat 66 -m "你好" --with-trace',
|
|
406
|
+
'wd-cli agent chat 66 -m "你好" --trace-only',
|
|
407
|
+
],
|
|
408
|
+
async run(ctx) {
|
|
409
|
+
const agentCode = ctx.args[0];
|
|
410
|
+
const messageRaw = ctx.flags.message;
|
|
411
|
+
const stream = Boolean(ctx.flags.stream);
|
|
412
|
+
const asJson = ctx.flags.output === 'json' || ctx.flags.json || ctx.flags.jq;
|
|
413
|
+
const withTrace = Boolean(ctx.flags.withTrace);
|
|
414
|
+
const traceOnly = Boolean(ctx.flags.traceOnly);
|
|
415
|
+
|
|
416
|
+
// 不给 --message 就进连续对话;但标准输入不是终端时(脚本 / 管道)保持报错,
|
|
417
|
+
// 免得 CI 里漏传 -m 的命令挂在那儿等输入。
|
|
418
|
+
const interactive = Boolean(ctx.flags.interactive) || messageRaw === undefined;
|
|
419
|
+
if (messageRaw === undefined && !process.stdin.isTTY) {
|
|
420
|
+
throw new CliError('缺少 --message', EXIT.USAGE, {
|
|
421
|
+
hint: '例:wd-cli agent chat 66 -m "你好";也可 -m - 从标准输入读;终端里不加 -m 即进入连续对话',
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// 没指定会话就先建一个:服务端按落库行校验 sessionId,自造的 id 一律 404
|
|
426
|
+
const sessionId = ctx.flags.sessionId || (await createSession(ctx, agentCode));
|
|
427
|
+
if (!ctx.flags.sessionId) {
|
|
428
|
+
output.info(`会话 id:${sessionId}(下次加 --session-id ${sessionId} 可接着聊)`, ctx.flags);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
if (messageRaw !== undefined) {
|
|
432
|
+
const message = String(dataInput.readDataText(messageRaw, '--message')).trim();
|
|
433
|
+
if (!message) throw new CliError('消息内容为空', EXIT.USAGE);
|
|
434
|
+
try {
|
|
435
|
+
await sendTurn(ctx, {
|
|
436
|
+
agentCode,
|
|
437
|
+
sessionId,
|
|
438
|
+
message,
|
|
439
|
+
stream,
|
|
440
|
+
asJson,
|
|
441
|
+
declaredSessionId: ctx.flags.sessionId,
|
|
442
|
+
withTrace,
|
|
443
|
+
traceOnly,
|
|
444
|
+
});
|
|
445
|
+
} catch (error) {
|
|
446
|
+
// 单次模式下这一轮就是全部,错误直接决定退出码;
|
|
447
|
+
// 要继续聊的话,首轮失败不该把后面的机会一起收走
|
|
448
|
+
if (!interactive) throw error;
|
|
449
|
+
output.warn(error.message, ctx.flags);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
if (interactive) {
|
|
454
|
+
await runInteractive(ctx, { agentCode, sessionId, stream, asJson, withTrace, traceOnly });
|
|
455
|
+
}
|
|
456
|
+
return EXIT.OK;
|
|
457
|
+
},
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
function readFileOrText(val, label) {
|
|
461
|
+
if (val === undefined || val === null) return null;
|
|
462
|
+
const s = String(val);
|
|
463
|
+
if (s === '-') return dataInput.readDataText('-', label);
|
|
464
|
+
if (s.startsWith('@')) return dataInput.readDataText(s, label);
|
|
465
|
+
if (fs.existsSync(s) && fs.statSync(s).isFile()) {
|
|
466
|
+
return fs.readFileSync(s, 'utf8');
|
|
467
|
+
}
|
|
468
|
+
return dataInput.readDataText(s, label);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
async function doPublishAgent(ctx, agentCode, remark) {
|
|
472
|
+
const body = remark ? { remark } : {};
|
|
473
|
+
const res = await http.request(ctx, {
|
|
474
|
+
method: 'POST',
|
|
475
|
+
path: `/agent/${encodeURIComponent(agentCode)}/publish`,
|
|
476
|
+
body,
|
|
477
|
+
});
|
|
478
|
+
output.print(res, { flags: ctx.flags });
|
|
479
|
+
const ver = res && (res.versionNumber || (res.data && res.data.versionNumber));
|
|
480
|
+
output.success(`Agent ${agentCode} 已成功发布${ver ? `(版本 V${ver})` : ''}`, ctx.flags);
|
|
481
|
+
return res;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function parseSkillIds(raw) {
|
|
485
|
+
if (raw === undefined || raw === null) return undefined;
|
|
486
|
+
const list = Array.isArray(raw) ? raw : [raw];
|
|
487
|
+
const ids = [];
|
|
488
|
+
for (const item of list) {
|
|
489
|
+
for (const part of String(item).split(',')) {
|
|
490
|
+
const trimmed = part.trim();
|
|
491
|
+
if (!trimmed) continue;
|
|
492
|
+
const num = Number(trimmed);
|
|
493
|
+
if (!Number.isFinite(num) || num <= 0) {
|
|
494
|
+
throw new CliError(`非法的 skillId:${trimmed},须为正整数`, EXIT.USAGE);
|
|
495
|
+
}
|
|
496
|
+
ids.push(num);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
return ids.length > 0 ? ids : undefined;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const create = {
|
|
503
|
+
name: 'create',
|
|
504
|
+
summary: '在当前工作空间新建 Agent(参数化或 YAML DSL 导入)',
|
|
505
|
+
principals: ['workspace'],
|
|
506
|
+
flags: {
|
|
507
|
+
name: { type: 'string', summary: 'Agent 名称(参数化创建时必填)' },
|
|
508
|
+
description: { type: 'string', summary: 'Agent 描述' },
|
|
509
|
+
type: { type: 'string', summary: '应用类型(缺省 agent)' },
|
|
510
|
+
prompt: { type: 'string', summary: 'System Prompt 提示词' },
|
|
511
|
+
'prompt-file': { type: 'string', summary: '从文件或标准输入(-)读取提示词' },
|
|
512
|
+
dsl: { type: 'string', summary: '从 YAML 文件或标准输入(-)读取完整 DSL 导入创建' },
|
|
513
|
+
'model-id': { type: 'number', summary: 'LLM 模型 ID' },
|
|
514
|
+
temperature: { type: 'number', summary: '模型采样温度 (0.0~2.0)' },
|
|
515
|
+
'max-tokens': { type: 'number', summary: '单次最大 Token 限制' },
|
|
516
|
+
'max-iterations': { type: 'number', summary: '最大迭代轮数' },
|
|
517
|
+
'max-iteration-count': { type: 'number', summary: '最大迭代轮数(等同 --max-iterations)' },
|
|
518
|
+
'skill-id': { type: 'string', repeat: true, summary: '初始绑定的技能 ID(可重复或逗号分隔)' },
|
|
519
|
+
'dry-run': { type: 'boolean', summary: '只打印将要提交的数据,不真正发起请求' },
|
|
520
|
+
publish: { type: 'boolean', summary: '创建成功后自动联动发布新版本' },
|
|
521
|
+
remark: { type: 'string', summary: '发布说明(配合 --publish 生效)' },
|
|
522
|
+
},
|
|
523
|
+
examples: [
|
|
524
|
+
'wd-cli agent create --name "数仓排障助手" --model-id 3 --prompt "你是数仓专家"',
|
|
525
|
+
'wd-cli agent create --name "数仓排障助手" --model-id 3 --prompt-file ./prompt.md --skill-id 128 --publish',
|
|
526
|
+
'wd-cli agent create --dsl ./agent.yaml --publish --remark "初始版本"',
|
|
527
|
+
],
|
|
528
|
+
async run(ctx) {
|
|
529
|
+
const {
|
|
530
|
+
name,
|
|
531
|
+
description,
|
|
532
|
+
type,
|
|
533
|
+
dsl,
|
|
534
|
+
prompt,
|
|
535
|
+
promptFile,
|
|
536
|
+
modelId,
|
|
537
|
+
temperature,
|
|
538
|
+
maxTokens,
|
|
539
|
+
maxIterations,
|
|
540
|
+
maxIterationCount,
|
|
541
|
+
skillId,
|
|
542
|
+
dryRun,
|
|
543
|
+
publish: shouldPublish,
|
|
544
|
+
remark: publishRemark,
|
|
545
|
+
} = ctx.flags;
|
|
546
|
+
|
|
547
|
+
if (dsl !== undefined) {
|
|
548
|
+
const yamlText = String(readFileOrText(dsl, '--dsl'));
|
|
549
|
+
if (dryRun) {
|
|
550
|
+
output.info('[dry-run] 将通过 DSL 新建 Agent' + (shouldPublish ? ' 并自动发布' : '') + ':\n' + yamlText, ctx.flags);
|
|
551
|
+
return EXIT.OK;
|
|
552
|
+
}
|
|
553
|
+
const created = await http.request(ctx, {
|
|
554
|
+
method: 'POST',
|
|
555
|
+
path: '/workspace-agents/dsl',
|
|
556
|
+
headers: { 'Content-Type': 'text/yaml' },
|
|
557
|
+
body: yamlText,
|
|
558
|
+
});
|
|
559
|
+
output.print(created, { flags: ctx.flags });
|
|
560
|
+
const newCode = created && (created.agentCode || created.agentId || created.id);
|
|
561
|
+
output.success(`已通过 DSL 创建 Agent:${newCode || ''}`, ctx.flags);
|
|
562
|
+
if (shouldPublish && newCode) {
|
|
563
|
+
await doPublishAgent(ctx, String(newCode), publishRemark);
|
|
564
|
+
}
|
|
565
|
+
return EXIT.OK;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
if (!name || !String(name).trim()) {
|
|
569
|
+
throw new CliError('必须指定 --name <名称> 或 --dsl <YAML文件>', EXIT.USAGE);
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
let effectivePrompt = prompt;
|
|
573
|
+
if (promptFile !== undefined) {
|
|
574
|
+
effectivePrompt = String(readFileOrText(promptFile, '--prompt-file'));
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
const payload = { name: String(name).trim() };
|
|
578
|
+
if (description !== undefined) payload.description = String(description);
|
|
579
|
+
if (type !== undefined) payload.appType = String(type);
|
|
580
|
+
if (effectivePrompt !== undefined) payload.prompt = effectivePrompt;
|
|
581
|
+
if (modelId !== undefined) payload.modelId = Number(modelId);
|
|
582
|
+
if (temperature !== undefined) payload.temperature = Number(temperature);
|
|
583
|
+
if (maxTokens !== undefined) payload.maxTokens = Number(maxTokens);
|
|
584
|
+
const iter = maxIterations !== undefined ? maxIterations : maxIterationCount;
|
|
585
|
+
if (iter !== undefined) payload.maxIterationCount = Number(iter);
|
|
586
|
+
const skillIds = parseSkillIds(skillId);
|
|
587
|
+
if (skillIds !== undefined) payload.skillIds = skillIds;
|
|
588
|
+
|
|
589
|
+
if (dryRun) {
|
|
590
|
+
output.info('[dry-run] 将创建 Agent' + (shouldPublish ? ' 并自动发布' : '') + ':\n' + JSON.stringify(payload, null, 2), ctx.flags);
|
|
591
|
+
return EXIT.OK;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
const created = await http.request(ctx, {
|
|
595
|
+
method: 'POST',
|
|
596
|
+
path: '/workspace-agents',
|
|
597
|
+
body: payload,
|
|
598
|
+
});
|
|
599
|
+
output.print(created, { flags: ctx.flags });
|
|
600
|
+
const newCode = created && (created.agentCode || created.agentId || created.id);
|
|
601
|
+
output.success(`已创建 Agent:${newCode || payload.name}`, ctx.flags);
|
|
602
|
+
if (shouldPublish && newCode) {
|
|
603
|
+
await doPublishAgent(ctx, String(newCode), publishRemark);
|
|
604
|
+
}
|
|
605
|
+
return EXIT.OK;
|
|
606
|
+
},
|
|
607
|
+
};
|
|
608
|
+
|
|
609
|
+
const publish = {
|
|
610
|
+
name: 'publish',
|
|
611
|
+
summary: '发布 Agent 编排为正式生效版本',
|
|
612
|
+
principals: ['workspace'],
|
|
613
|
+
args: [{ name: 'agentCode', required: true, summary: 'Agent ID 或 agentId#versionId' }],
|
|
614
|
+
flags: {
|
|
615
|
+
remark: { type: 'string', summary: '发布说明(版本备注)' },
|
|
616
|
+
},
|
|
617
|
+
examples: [
|
|
618
|
+
'wd-cli agent publish 66',
|
|
619
|
+
'wd-cli agent publish 66 --remark "发布最新提示词与模型参数"',
|
|
620
|
+
],
|
|
621
|
+
async run(ctx) {
|
|
622
|
+
const agentCode = ctx.args[0];
|
|
623
|
+
await doPublishAgent(ctx, agentCode, ctx.flags.remark);
|
|
624
|
+
return EXIT.OK;
|
|
625
|
+
},
|
|
626
|
+
};
|
|
627
|
+
|
|
628
|
+
const update = {
|
|
629
|
+
name: 'update',
|
|
630
|
+
summary: '更新 Agent 编排(增量配置或全量 DSL)',
|
|
631
|
+
principals: ['workspace'],
|
|
632
|
+
args: [{ name: 'agentCode', required: true, summary: 'Agent ID 或 agentId#versionId' }],
|
|
633
|
+
flags: {
|
|
634
|
+
prompt: { type: 'string', summary: 'System Prompt 提示词' },
|
|
635
|
+
'prompt-file': { type: 'string', summary: '从文件或标准输入(-)读取提示词' },
|
|
636
|
+
dsl: { type: 'string', summary: '从 YAML 文件或标准输入(-)读取完整 DSL 覆盖更新' },
|
|
637
|
+
'model-id': { type: 'number', summary: 'LLM 模型 ID' },
|
|
638
|
+
temperature: { type: 'number', summary: '模型采样温度 (0.0~2.0)' },
|
|
639
|
+
'max-tokens': { type: 'number', summary: '单次最大 Token 限制' },
|
|
640
|
+
'max-iterations': { type: 'number', summary: '最大迭代轮数' },
|
|
641
|
+
'max-iteration-count': { type: 'number', summary: '最大迭代轮数(等同 --max-iterations)' },
|
|
642
|
+
'dry-run': { type: 'boolean', summary: '只打印将要提交的数据,不真正发起请求' },
|
|
643
|
+
publish: { type: 'boolean', summary: '更新成功后自动联动发布新版本' },
|
|
644
|
+
remark: { type: 'string', summary: '发布说明(配合 --publish 生效)' },
|
|
645
|
+
},
|
|
646
|
+
examples: [
|
|
647
|
+
'wd-cli agent update 66 --prompt "你是智能助手"',
|
|
648
|
+
'wd-cli agent update 66 --prompt-file ./prompt.txt --temperature 0.7',
|
|
649
|
+
'wd-cli agent update 66 --dsl ./agent.yaml',
|
|
650
|
+
'wd-cli agent update 66 --dsl - < ./agent.yaml --dry-run',
|
|
651
|
+
'wd-cli agent update 66 --dsl ./agent.yaml --publish --remark "发布更新"',
|
|
652
|
+
],
|
|
653
|
+
async run(ctx) {
|
|
654
|
+
const agentCode = ctx.args[0];
|
|
655
|
+
const { dsl, prompt, promptFile, modelId, temperature, maxTokens, maxIterations, maxIterationCount, dryRun, publish: shouldPublish, remark: publishRemark } = ctx.flags;
|
|
656
|
+
|
|
657
|
+
if (dsl !== undefined) {
|
|
658
|
+
const yamlText = String(readFileOrText(dsl, '--dsl'));
|
|
659
|
+
if (dryRun) {
|
|
660
|
+
output.info('[dry-run] 将通过 DSL 覆盖更新 Agent' + (shouldPublish ? ' 并自动发布' : '') + ':\n' + yamlText, ctx.flags);
|
|
661
|
+
return EXIT.OK;
|
|
662
|
+
}
|
|
663
|
+
const updated = await http.request(ctx, {
|
|
664
|
+
method: 'PUT',
|
|
665
|
+
path: `/agent/${encodeURIComponent(agentCode)}/dsl`,
|
|
666
|
+
headers: { 'Content-Type': 'text/yaml' },
|
|
667
|
+
body: yamlText,
|
|
668
|
+
});
|
|
669
|
+
output.print(updated, { flags: ctx.flags });
|
|
670
|
+
output.success(`Agent ${agentCode} DSL 已更新`, ctx.flags);
|
|
671
|
+
if (shouldPublish) {
|
|
672
|
+
await doPublishAgent(ctx, agentCode, publishRemark);
|
|
673
|
+
}
|
|
674
|
+
return EXIT.OK;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
let effectivePrompt = prompt;
|
|
678
|
+
if (promptFile !== undefined) {
|
|
679
|
+
effectivePrompt = String(readFileOrText(promptFile, '--prompt-file'));
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
const payload = {};
|
|
683
|
+
if (effectivePrompt !== undefined) payload.prompt = effectivePrompt;
|
|
684
|
+
if (modelId !== undefined) payload.modelId = Number(modelId);
|
|
685
|
+
if (temperature !== undefined) payload.temperature = Number(temperature);
|
|
686
|
+
if (maxTokens !== undefined) payload.maxTokens = Number(maxTokens);
|
|
687
|
+
const iter = maxIterations !== undefined ? maxIterations : maxIterationCount;
|
|
688
|
+
if (iter !== undefined) payload.maxIterationCount = Number(iter);
|
|
689
|
+
|
|
690
|
+
if (Object.keys(payload).length === 0) {
|
|
691
|
+
throw new CliError('未指定任何更新字段(需指定 --prompt, --prompt-file, --dsl, --model-id 等)', EXIT.USAGE);
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
if (dryRun) {
|
|
695
|
+
output.info('[dry-run] 将提交增量编排配置' + (shouldPublish ? ' 并自动发布' : '') + ':\n' + JSON.stringify(payload, null, 2), ctx.flags);
|
|
696
|
+
return EXIT.OK;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
const updated = await http.request(ctx, {
|
|
700
|
+
method: 'PUT',
|
|
701
|
+
path: `/agent/${encodeURIComponent(agentCode)}/orchestration`,
|
|
702
|
+
body: payload,
|
|
703
|
+
});
|
|
704
|
+
output.print(updated, { flags: ctx.flags });
|
|
705
|
+
output.success(`Agent ${agentCode} 编排配置已更新`, ctx.flags);
|
|
706
|
+
if (shouldPublish) {
|
|
707
|
+
await doPublishAgent(ctx, agentCode, publishRemark);
|
|
708
|
+
}
|
|
709
|
+
return EXIT.OK;
|
|
710
|
+
},
|
|
711
|
+
};
|
|
712
|
+
|
|
713
|
+
const bindSkill = {
|
|
714
|
+
name: 'bind-skill',
|
|
715
|
+
summary: '为 Agent 绑定工作空间技能',
|
|
716
|
+
principals: ['workspace'],
|
|
717
|
+
args: [
|
|
718
|
+
{ name: 'agentCode', required: true, summary: 'Agent ID' },
|
|
719
|
+
{ name: 'skillId', required: false, summary: '待绑定的技能 ID(也可通过 --skill-id 指定)' },
|
|
720
|
+
],
|
|
721
|
+
flags: {
|
|
722
|
+
'skill-id': { type: 'number', summary: '待绑定的技能 ID' },
|
|
723
|
+
},
|
|
724
|
+
examples: ['wd-cli agent bind-skill 66 128', 'wd-cli agent bind-skill 66 --skill-id 128'],
|
|
725
|
+
async run(ctx) {
|
|
726
|
+
const agentCode = ctx.args[0];
|
|
727
|
+
const skillIdRaw = ctx.flags?.skillId !== undefined ? ctx.flags.skillId : (ctx.flags?.['skill-id'] !== undefined ? ctx.flags['skill-id'] : ctx.args[1]);
|
|
728
|
+
const skillId = Number(skillIdRaw);
|
|
729
|
+
if (!skillId || Number.isNaN(skillId)) {
|
|
730
|
+
throw new CliError('必须指定合法的 skillId(位置参数或 --skill-id),须为正整数', EXIT.USAGE);
|
|
731
|
+
}
|
|
732
|
+
const res = await http.request(ctx, {
|
|
733
|
+
method: 'POST',
|
|
734
|
+
path: `/agent/${encodeURIComponent(agentCode)}/skills/bind`,
|
|
735
|
+
body: { skillId },
|
|
736
|
+
});
|
|
737
|
+
output.print(res, { flags: ctx.flags });
|
|
738
|
+
output.success(`已为 Agent ${agentCode} 绑定技能 ${skillId}`, ctx.flags);
|
|
739
|
+
return EXIT.OK;
|
|
740
|
+
},
|
|
741
|
+
};
|
|
742
|
+
|
|
743
|
+
const unbindSkill = {
|
|
744
|
+
name: 'unbind-skill',
|
|
745
|
+
summary: '从 Agent 解绑技能',
|
|
746
|
+
principals: ['workspace'],
|
|
747
|
+
args: [
|
|
748
|
+
{ name: 'agentCode', required: true, summary: 'Agent ID' },
|
|
749
|
+
{ name: 'skillId', required: false, summary: '待解绑的技能 ID(也可通过 --skill-id 指定)' },
|
|
750
|
+
],
|
|
751
|
+
flags: {
|
|
752
|
+
'skill-id': { type: 'number', summary: '待解绑的技能 ID' },
|
|
753
|
+
},
|
|
754
|
+
examples: ['wd-cli agent unbind-skill 66 128', 'wd-cli agent unbind-skill 66 --skill-id 128'],
|
|
755
|
+
async run(ctx) {
|
|
756
|
+
const agentCode = ctx.args[0];
|
|
757
|
+
const skillIdRaw = ctx.flags?.skillId !== undefined ? ctx.flags.skillId : (ctx.flags?.['skill-id'] !== undefined ? ctx.flags['skill-id'] : ctx.args[1]);
|
|
758
|
+
const skillId = Number(skillIdRaw);
|
|
759
|
+
if (!skillId || Number.isNaN(skillId)) {
|
|
760
|
+
throw new CliError('必须指定合法的 skillId(位置参数或 --skill-id),须为正整数', EXIT.USAGE);
|
|
761
|
+
}
|
|
762
|
+
const res = await http.request(ctx, {
|
|
763
|
+
method: 'POST',
|
|
764
|
+
path: `/agent/${encodeURIComponent(agentCode)}/skills/unbind`,
|
|
765
|
+
body: { skillId },
|
|
766
|
+
});
|
|
767
|
+
output.print(res, { flags: ctx.flags });
|
|
768
|
+
output.success(`已从 Agent ${agentCode} 解绑技能 ${skillId}`, ctx.flags);
|
|
769
|
+
return EXIT.OK;
|
|
770
|
+
},
|
|
771
|
+
};
|
|
772
|
+
|
|
773
|
+
module.exports = {
|
|
774
|
+
id: 'agent',
|
|
775
|
+
summary: '应用:列表 / 信息 / 元数据 / 对话 / 编排维护',
|
|
776
|
+
description: '对话端点在 server/gateway;与其余 Open API 不同域名时用 wd-cli config set chatBaseUrl 指定。',
|
|
777
|
+
principals: ['agent'],
|
|
778
|
+
commands: [list, create, info, metadata, revision, model, chat, update, publish, bindSkill, unbindSkill],
|
|
779
|
+
extractDelta,
|
|
780
|
+
isFinished,
|
|
781
|
+
errorMessage,
|
|
782
|
+
extractTraceId,
|
|
783
|
+
};
|
|
784
|
+
|