@dmall-inc/wd-cli 0.1.0 → 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 +38 -2
- package/lib/commands/agent.js +419 -20
- package/lib/commands/observability.js +241 -0
- package/lib/commands/skill.js +124 -2
- package/lib/http.js +8 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# @dmall-inc/wd-cli
|
|
2
2
|
|
|
3
|
+
[](https://www.npmjs.com/package/@dmall-inc/wd-cli)
|
|
4
|
+
|
|
3
5
|
水滴平台的命令行工具。用统一身份登录一次,选定工作空间,就能在终端里访问平台上你看得到的技能、知识库、应用、会话、评测与可观测数据。
|
|
4
6
|
|
|
5
7
|
```bash
|
|
@@ -14,6 +16,24 @@ wd-cli skill list
|
|
|
14
16
|
|
|
15
17
|
需要 Node.js 18 或更高版本。零运行时依赖。
|
|
16
18
|
|
|
19
|
+
### 安装
|
|
20
|
+
|
|
21
|
+
包已发布到 npm 公共仓库:[npmjs.com/package/@dmall-inc/wd-cli](https://www.npmjs.com/package/@dmall-inc/wd-cli)。
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm i -g @dmall-inc/wd-cli # 安装最新版
|
|
25
|
+
npm i -g @dmall-inc/wd-cli@0.1.0 # 指定版本
|
|
26
|
+
npm update -g @dmall-inc/wd-cli # 升级
|
|
27
|
+
npm view @dmall-inc/wd-cli versions # 查看已发布版本
|
|
28
|
+
wd-cli --version # 确认本地版本
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
本机 npm 若指向内部镜像且拉不到这个包,显式指定公共仓库:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
npm i -g @dmall-inc/wd-cli --registry https://registry.npmjs.org
|
|
35
|
+
```
|
|
36
|
+
|
|
17
37
|
---
|
|
18
38
|
|
|
19
39
|
## 目录
|
|
@@ -202,15 +222,22 @@ wd-cli kb share create|list 12 99
|
|
|
202
222
|
wd-cli agent list
|
|
203
223
|
wd-cli agent list --q 客服 --published
|
|
204
224
|
wd-cli agent list --type high-agent --paginate --json agentCode,name
|
|
225
|
+
|
|
226
|
+
wd-cli agent create --name "数仓排障助手" --model-id 3 --prompt-file ./prompt.md --skill-id 128 --publish
|
|
227
|
+
wd-cli agent create --dsl ./agent.yaml --publish --remark "初始版本"
|
|
205
228
|
```
|
|
206
229
|
|
|
207
|
-
`agent list` 列出当前工作空间的应用,按更新时间倒序;可见范围与平台界面一致(工作空间成员能看到空间内全部应用)。`--published` 只留已发布的,也就是能拿去对话的;`--type` 直接用列表里「类型」列的值。输出里的 ID 就是后续命令要的 agentCode
|
|
230
|
+
`agent list` 列出当前工作空间的应用,按更新时间倒序;可见范围与平台界面一致(工作空间成员能看到空间内全部应用)。`--published` 只留已发布的,也就是能拿去对话的;`--type` 直接用列表里「类型」列的值。输出里的 ID 就是后续命令要的 agentCode。`agent create` 支持参数化或从 YAML DSL 新建 Agent(需工作空间构建权限),加 `--publish` 可一步完成首版发布上线。登录态或工作空间令牌可用,应用访问密钥不行——它只代表单个应用。
|
|
208
231
|
|
|
209
232
|
```bash
|
|
210
233
|
wd-cli agent info --agent-code 66
|
|
211
234
|
wd-cli agent metadata 66
|
|
212
235
|
wd-cli agent revision 66
|
|
213
236
|
wd-cli agent model 3 --agent-code 66
|
|
237
|
+
wd-cli agent update 66 --prompt-file ./prompt.md --publish
|
|
238
|
+
wd-cli agent publish 66 --remark "发布新版"
|
|
239
|
+
wd-cli agent bind-skill 66 --skill-id 128
|
|
240
|
+
wd-cli agent unbind-skill 66 --skill-id 128
|
|
214
241
|
|
|
215
242
|
wd-cli agent chat 66
|
|
216
243
|
wd-cli agent chat 66 -m "你好"
|
|
@@ -361,6 +388,15 @@ npm test # 全量测试,离线跑,不碰真实服务
|
|
|
361
388
|
|
|
362
389
|
测试用进程内的 mock 平台与 mock 认证中心,跑的是真实入口进程,验的是退出码与标准输出 / 标准错误的实际分工。
|
|
363
390
|
|
|
364
|
-
|
|
391
|
+
发布到 npm 公共仓库([@dmall-inc/wd-cli](https://www.npmjs.com/package/@dmall-inc/wd-cli),需 `@dmall-inc` 组织的发布权限):
|
|
392
|
+
|
|
393
|
+
```bash
|
|
394
|
+
npm login --registry https://registry.npmjs.org
|
|
395
|
+
npm version patch # 或 minor / major,改 package.json 的 version
|
|
396
|
+
npm publish --access public --registry https://registry.npmjs.org
|
|
397
|
+
npm view @dmall-inc/wd-cli version --registry https://registry.npmjs.org # 确认已上线
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
scoped 包默认按私有发布,首次发布必须带 `--access public`。发布内容由 `package.json` 的 `files` 决定(`bin`、`lib`、`docs`、`README.md`),发布前可用 `npm pack --dry-run` 核对。
|
|
365
401
|
|
|
366
402
|
设计取舍与对标的项目(`gh`、`gcloud`、`kubectl`、AWS CLI、clig.dev)见 [`docs/design-references.md`](./docs/design-references.md)。
|
package/lib/commands/agent.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* 拆开部署则用 profile 的 chatBaseUrl 指过去。
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
+
const fs = require('node:fs');
|
|
14
15
|
const readline = require('node:readline');
|
|
15
16
|
|
|
16
17
|
const http = require('../http');
|
|
@@ -34,6 +35,26 @@ function isFinished(payload) {
|
|
|
34
35
|
return /RUN_FINISHED|done|finish/i.test(type);
|
|
35
36
|
}
|
|
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
|
+
|
|
37
58
|
const AGENT_COLUMNS = [
|
|
38
59
|
{ key: 'agentCode', label: 'ID' },
|
|
39
60
|
{ key: 'name', label: '名称' },
|
|
@@ -185,12 +206,14 @@ const model = {
|
|
|
185
206
|
* 发一轮对话,回复写标准输出。单次与连续对话共用这一条路径。
|
|
186
207
|
* 出错一律抛 CliError:单次模式直接决定退出码,连续对话里由调用方接住、只报一轮失败。
|
|
187
208
|
*/
|
|
188
|
-
async function sendTurn(ctx, { agentCode, sessionId, message, stream, asJson, declaredSessionId }) {
|
|
209
|
+
async function sendTurn(ctx, { agentCode, sessionId, message, stream, asJson, declaredSessionId, withTrace, traceOnly }) {
|
|
189
210
|
const path = `/${encodeURIComponent(agentCode)}/chat`;
|
|
190
211
|
const onError = (error) => {
|
|
191
212
|
throw explainMissingSession(error, declaredSessionId);
|
|
192
213
|
};
|
|
193
214
|
|
|
215
|
+
let traceId = null;
|
|
216
|
+
|
|
194
217
|
if (!stream) {
|
|
195
218
|
const result = await http
|
|
196
219
|
.request(ctx, {
|
|
@@ -198,29 +221,56 @@ async function sendTurn(ctx, { agentCode, sessionId, message, stream, asJson, de
|
|
|
198
221
|
base: ctx.chatBase(),
|
|
199
222
|
path,
|
|
200
223
|
body: { sessionId, message, mode: 'block' },
|
|
224
|
+
onResponse: (res) => {
|
|
225
|
+
const tid = extractTraceId(null, res.headers);
|
|
226
|
+
if (tid) traceId = tid;
|
|
227
|
+
},
|
|
201
228
|
})
|
|
202
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
|
+
|
|
203
240
|
const text =
|
|
204
241
|
result && typeof result === 'object'
|
|
205
242
|
? result.reply ?? result.message ?? result.content ?? JSON.stringify(result)
|
|
206
243
|
: result;
|
|
244
|
+
|
|
245
|
+
if (asJson) {
|
|
246
|
+
output.print({ reply: text, sessionId, traceId: traceId || null }, { flags: ctx.flags });
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
|
|
207
250
|
output.print(text, { flags: ctx.flags });
|
|
251
|
+
if (withTrace && traceId) {
|
|
252
|
+
process.stdout.write(`[TraceId: ${traceId}]\n`);
|
|
253
|
+
}
|
|
208
254
|
return;
|
|
209
255
|
}
|
|
210
256
|
|
|
211
257
|
let failure = null;
|
|
212
258
|
let wroteAny = false;
|
|
259
|
+
let replyText = '';
|
|
213
260
|
await http
|
|
214
261
|
.stream(ctx, {
|
|
215
262
|
method: 'POST',
|
|
216
263
|
base: ctx.chatBase(),
|
|
217
264
|
path,
|
|
218
265
|
body: { sessionId, message, mode: 'stream' },
|
|
266
|
+
onResponse: (res) => {
|
|
267
|
+
const tid = extractTraceId(null, res.headers);
|
|
268
|
+
if (tid) traceId = tid;
|
|
269
|
+
},
|
|
219
270
|
onEvent: ({ data }) => {
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
}
|
|
271
|
+
const tid = extractTraceId(data);
|
|
272
|
+
if (tid) traceId = tid;
|
|
273
|
+
|
|
224
274
|
const error = errorMessage(data);
|
|
225
275
|
if (error) {
|
|
226
276
|
failure = error;
|
|
@@ -228,14 +278,32 @@ async function sendTurn(ctx, { agentCode, sessionId, message, stream, asJson, de
|
|
|
228
278
|
}
|
|
229
279
|
const delta = extractDelta(data);
|
|
230
280
|
if (delta) {
|
|
231
|
-
|
|
232
|
-
|
|
281
|
+
replyText += String(delta);
|
|
282
|
+
if (!asJson && !traceOnly) {
|
|
283
|
+
process.stdout.write(String(delta));
|
|
284
|
+
wroteAny = true;
|
|
285
|
+
}
|
|
233
286
|
}
|
|
234
287
|
},
|
|
235
288
|
})
|
|
236
289
|
.catch(onError);
|
|
237
|
-
|
|
290
|
+
|
|
238
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
|
+
}
|
|
239
307
|
}
|
|
240
308
|
|
|
241
309
|
/** 连续对话里可用的斜杠命令,供提示与补全。 */
|
|
@@ -253,7 +321,7 @@ function printReplHelp(ctx) {
|
|
|
253
321
|
* 提示符与所有提示走标准错误,回复走标准输出——这样 `wd-cli agent chat 66 > out.txt`
|
|
254
322
|
* 仍只把回复落进文件(clig.dev)。Ctrl-D(EOF)与 /exit 都能正常收尾。
|
|
255
323
|
*/
|
|
256
|
-
async function runInteractive(ctx, { agentCode, sessionId, stream, asJson }) {
|
|
324
|
+
async function runInteractive(ctx, { agentCode, sessionId, stream, asJson, withTrace, traceOnly }) {
|
|
257
325
|
const rl = readline.createInterface({
|
|
258
326
|
input: process.stdin,
|
|
259
327
|
output: process.stderr,
|
|
@@ -266,24 +334,30 @@ async function runInteractive(ctx, { agentCode, sessionId, stream, asJson }) {
|
|
|
266
334
|
// Ctrl-C 结束当前 REPL,而不是让 readline 默认继续等输入
|
|
267
335
|
rl.on('SIGINT', () => rl.close());
|
|
268
336
|
|
|
337
|
+
function safePrompt() {
|
|
338
|
+
try {
|
|
339
|
+
if (!rl.closed) rl.prompt();
|
|
340
|
+
} catch {}
|
|
341
|
+
}
|
|
342
|
+
|
|
269
343
|
output.info('连续对话已开始,/help 看可用命令,/exit 或 Ctrl-D 退出。', ctx.flags);
|
|
270
344
|
let current = sessionId;
|
|
271
|
-
|
|
345
|
+
safePrompt();
|
|
272
346
|
for await (const raw of rl) {
|
|
273
347
|
const line = String(raw).trim();
|
|
274
348
|
if (!line) {
|
|
275
|
-
|
|
349
|
+
safePrompt();
|
|
276
350
|
continue;
|
|
277
351
|
}
|
|
278
352
|
if (line === '/exit' || line === '/quit') break;
|
|
279
353
|
if (line === '/help') {
|
|
280
354
|
printReplHelp(ctx);
|
|
281
|
-
|
|
355
|
+
safePrompt();
|
|
282
356
|
continue;
|
|
283
357
|
}
|
|
284
358
|
if (line === '/session') {
|
|
285
359
|
output.info(`当前会话:${current}`, ctx.flags);
|
|
286
|
-
|
|
360
|
+
safePrompt();
|
|
287
361
|
continue;
|
|
288
362
|
}
|
|
289
363
|
if (line === '/new') {
|
|
@@ -293,18 +367,20 @@ async function runInteractive(ctx, { agentCode, sessionId, stream, asJson }) {
|
|
|
293
367
|
} catch (error) {
|
|
294
368
|
output.warn(`建会话失败:${error.message}`, ctx.flags);
|
|
295
369
|
}
|
|
296
|
-
|
|
370
|
+
safePrompt();
|
|
297
371
|
continue;
|
|
298
372
|
}
|
|
299
373
|
try {
|
|
300
374
|
// 会话是这里建/接手的,一轮失败不该把整个对话带走,故不传 declaredSessionId
|
|
301
|
-
await sendTurn(ctx, { agentCode, sessionId: current, message: line, stream, asJson });
|
|
375
|
+
await sendTurn(ctx, { agentCode, sessionId: current, message: line, stream, asJson, withTrace, traceOnly });
|
|
302
376
|
} catch (error) {
|
|
303
377
|
output.warn(error.message, ctx.flags);
|
|
304
378
|
}
|
|
305
|
-
|
|
379
|
+
safePrompt();
|
|
306
380
|
}
|
|
307
|
-
|
|
381
|
+
try {
|
|
382
|
+
if (!rl.closed) rl.close();
|
|
383
|
+
} catch {}
|
|
308
384
|
output.info(`对话结束。下次接着聊:wd-cli agent chat ${agentCode} --session-id ${current}`, ctx.flags);
|
|
309
385
|
}
|
|
310
386
|
|
|
@@ -317,6 +393,8 @@ const chat = {
|
|
|
317
393
|
'session-id': { type: 'string', summary: '接着已有会话聊;缺省自动新建一个并在标准错误提示 id' },
|
|
318
394
|
stream: { type: 'boolean', summary: '流式输出(消费 AG-UI 事件)' },
|
|
319
395
|
interactive: { type: 'boolean', short: 'i', summary: '发完 --message 后继续连续对话' },
|
|
396
|
+
'with-trace': { type: 'boolean', summary: '输出中附带本次会话关联的 traceId' },
|
|
397
|
+
'trace-only': { type: 'boolean', summary: '仅输出 traceId' },
|
|
320
398
|
},
|
|
321
399
|
examples: [
|
|
322
400
|
'wd-cli agent chat 66',
|
|
@@ -324,12 +402,16 @@ const chat = {
|
|
|
324
402
|
'wd-cli agent chat 66 -m "写一段介绍" --stream',
|
|
325
403
|
'wd-cli agent chat 66 -i --stream',
|
|
326
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',
|
|
327
407
|
],
|
|
328
408
|
async run(ctx) {
|
|
329
409
|
const agentCode = ctx.args[0];
|
|
330
410
|
const messageRaw = ctx.flags.message;
|
|
331
411
|
const stream = Boolean(ctx.flags.stream);
|
|
332
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);
|
|
333
415
|
|
|
334
416
|
// 不给 --message 就进连续对话;但标准输入不是终端时(脚本 / 管道)保持报错,
|
|
335
417
|
// 免得 CI 里漏传 -m 的命令挂在那儿等输入。
|
|
@@ -357,6 +439,8 @@ const chat = {
|
|
|
357
439
|
stream,
|
|
358
440
|
asJson,
|
|
359
441
|
declaredSessionId: ctx.flags.sessionId,
|
|
442
|
+
withTrace,
|
|
443
|
+
traceOnly,
|
|
360
444
|
});
|
|
361
445
|
} catch (error) {
|
|
362
446
|
// 单次模式下这一轮就是全部,错误直接决定退出码;
|
|
@@ -367,19 +451,334 @@ const chat = {
|
|
|
367
451
|
}
|
|
368
452
|
|
|
369
453
|
if (interactive) {
|
|
370
|
-
await runInteractive(ctx, { agentCode, sessionId, stream, asJson });
|
|
454
|
+
await runInteractive(ctx, { agentCode, sessionId, stream, asJson, withTrace, traceOnly });
|
|
371
455
|
}
|
|
372
456
|
return EXIT.OK;
|
|
373
457
|
},
|
|
374
458
|
};
|
|
375
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
|
+
|
|
376
773
|
module.exports = {
|
|
377
774
|
id: 'agent',
|
|
378
|
-
summary: '应用:列表 / 信息 / 元数据 / 对话',
|
|
775
|
+
summary: '应用:列表 / 信息 / 元数据 / 对话 / 编排维护',
|
|
379
776
|
description: '对话端点在 server/gateway;与其余 Open API 不同域名时用 wd-cli config set chatBaseUrl 指定。',
|
|
380
777
|
principals: ['agent'],
|
|
381
|
-
commands: [list, info, metadata, revision, model, chat],
|
|
778
|
+
commands: [list, create, info, metadata, revision, model, chat, update, publish, bindSkill, unbindSkill],
|
|
382
779
|
extractDelta,
|
|
383
780
|
isFinished,
|
|
384
781
|
errorMessage,
|
|
782
|
+
extractTraceId,
|
|
385
783
|
};
|
|
784
|
+
|
|
@@ -81,6 +81,35 @@ const traceTopic = {
|
|
|
81
81
|
return EXIT.OK;
|
|
82
82
|
},
|
|
83
83
|
},
|
|
84
|
+
{
|
|
85
|
+
name: 'summary',
|
|
86
|
+
summary: '查看单条调用链的诊断摘要(提炼 CoT 推理、工具调用与异常)',
|
|
87
|
+
args: [agentArg, { name: 'traceId', required: true, summary: 'trace id' }],
|
|
88
|
+
flags: {
|
|
89
|
+
format: { type: 'string', summary: '输出格式:markdown(缺省)| json | text' },
|
|
90
|
+
},
|
|
91
|
+
examples: [
|
|
92
|
+
'wd-cli trace summary 66 abc123',
|
|
93
|
+
'wd-cli trace summary 66 abc123 --format json',
|
|
94
|
+
],
|
|
95
|
+
async run(ctx) {
|
|
96
|
+
const agentCode = ctx.args[0];
|
|
97
|
+
const traceId = ctx.args[1];
|
|
98
|
+
const spans = await http.request(ctx, {
|
|
99
|
+
path: `/observability/${encodeURIComponent(agentCode)}/traces/${encodeURIComponent(traceId)}`,
|
|
100
|
+
});
|
|
101
|
+
const summary = analyzeTraceSpans(traceId, spans);
|
|
102
|
+
const format = ctx.flags.format || (ctx.flags.output === 'json' || ctx.flags.json ? 'json' : 'markdown');
|
|
103
|
+
if (format === 'json') {
|
|
104
|
+
output.print(summary, { flags: ctx.flags });
|
|
105
|
+
} else if (format === 'text') {
|
|
106
|
+
process.stdout.write(`${renderSummaryText(summary)}\n`);
|
|
107
|
+
} else {
|
|
108
|
+
process.stdout.write(`${renderSummaryMarkdown(summary)}\n`);
|
|
109
|
+
}
|
|
110
|
+
return EXIT.OK;
|
|
111
|
+
},
|
|
112
|
+
},
|
|
84
113
|
],
|
|
85
114
|
};
|
|
86
115
|
|
|
@@ -135,6 +164,218 @@ const scoreTopic = {
|
|
|
135
164
|
],
|
|
136
165
|
};
|
|
137
166
|
|
|
167
|
+
function parseAttributes(attr) {
|
|
168
|
+
if (!attr) return {};
|
|
169
|
+
let current = attr;
|
|
170
|
+
for (let i = 0; i < 5 && typeof current === 'string'; i++) {
|
|
171
|
+
try {
|
|
172
|
+
current = JSON.parse(current);
|
|
173
|
+
} catch {
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (Array.isArray(current)) {
|
|
178
|
+
const res = {};
|
|
179
|
+
for (const item of current) {
|
|
180
|
+
if (item && typeof item === 'object') {
|
|
181
|
+
const k = item.key || item.Key || item.name;
|
|
182
|
+
const v = item.value !== undefined ? item.value : (item.Value !== undefined ? item.Value : item);
|
|
183
|
+
if (k) res[k] = v;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return res;
|
|
187
|
+
}
|
|
188
|
+
if (current && typeof current === 'object') {
|
|
189
|
+
return current;
|
|
190
|
+
}
|
|
191
|
+
return {};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function safeJsonOrString(val) {
|
|
195
|
+
if (val === undefined || val === null) return '';
|
|
196
|
+
if (typeof val === 'object') return val;
|
|
197
|
+
try {
|
|
198
|
+
return JSON.parse(val);
|
|
199
|
+
} catch {
|
|
200
|
+
return val;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function analyzeTraceSpans(traceId, rawSpans) {
|
|
205
|
+
const spans = Array.isArray(rawSpans) ? rawSpans : [];
|
|
206
|
+
let overallStatus = 'OK';
|
|
207
|
+
let totalDurationMs = 0;
|
|
208
|
+
const thoughts = [];
|
|
209
|
+
const toolCalls = [];
|
|
210
|
+
const errors = [];
|
|
211
|
+
|
|
212
|
+
for (const span of spans) {
|
|
213
|
+
const isError =
|
|
214
|
+
span.statusCode === 'ERROR' ||
|
|
215
|
+
span.statusCode === 'STATUS_CODE_ERROR' ||
|
|
216
|
+
(span.statusCode !== 'OK' &&
|
|
217
|
+
span.statusCode !== 'STATUS_CODE_OK' &&
|
|
218
|
+
span.statusMessage &&
|
|
219
|
+
/error|failed|exception/i.test(span.statusMessage));
|
|
220
|
+
if (isError) {
|
|
221
|
+
overallStatus = 'ERROR';
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const durMs = span.duration ? Math.round(Number(span.duration) / 1_000_000) : 0;
|
|
225
|
+
if (!span.parentSpanId && durMs > totalDurationMs) {
|
|
226
|
+
totalDurationMs = durMs;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const attrs = parseAttributes(span.spanAttributes);
|
|
230
|
+
|
|
231
|
+
// 提炼 CoT 推理(Thinking / Reasoning)
|
|
232
|
+
const thoughtVal =
|
|
233
|
+
attrs['llm.thought'] ||
|
|
234
|
+
attrs.thought ||
|
|
235
|
+
attrs.thinking ||
|
|
236
|
+
attrs.reasoning ||
|
|
237
|
+
attrs.reasoning_content ||
|
|
238
|
+
attrs['openinference.thought'] ||
|
|
239
|
+
attrs['gen_ai.thought'];
|
|
240
|
+
if (thoughtVal) {
|
|
241
|
+
const thoughtStr = typeof thoughtVal === 'object' ? JSON.stringify(thoughtVal) : String(thoughtVal);
|
|
242
|
+
const trimmed = thoughtStr.trim();
|
|
243
|
+
if (trimmed && !thoughts.includes(trimmed)) {
|
|
244
|
+
thoughts.push(trimmed);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// 提炼工具调用(Tool Calls)
|
|
249
|
+
const isTool =
|
|
250
|
+
String(span.spanKind).toLowerCase() === 'tool' ||
|
|
251
|
+
String(attrs['openinference.span.kind']).toUpperCase() === 'TOOL' ||
|
|
252
|
+
String(attrs['span.kind']).toUpperCase() === 'TOOL' ||
|
|
253
|
+
(span.spanName && (span.spanName.startsWith('execute_tool') || span.spanName.includes('tool'))) ||
|
|
254
|
+
attrs['tool.name'] ||
|
|
255
|
+
attrs['gen_ai.tool.name'];
|
|
256
|
+
|
|
257
|
+
if (isTool) {
|
|
258
|
+
const toolName =
|
|
259
|
+
attrs['tool.name'] ||
|
|
260
|
+
attrs['gen_ai.tool.name'] ||
|
|
261
|
+
(span.spanName ? span.spanName.replace(/^execute_tool:?/, '').trim() : 'unknown');
|
|
262
|
+
const toolArgsRaw =
|
|
263
|
+
attrs['tool.parameters'] ||
|
|
264
|
+
attrs['tool.arguments'] ||
|
|
265
|
+
attrs['gen_ai.tool.call.arguments'] ||
|
|
266
|
+
attrs.input ||
|
|
267
|
+
attrs['input.value'] ||
|
|
268
|
+
attrs['gen_ai.task.input'];
|
|
269
|
+
const toolArgs = safeJsonOrString(toolArgsRaw);
|
|
270
|
+
|
|
271
|
+
const toolResultRaw =
|
|
272
|
+
attrs['tool.result'] ||
|
|
273
|
+
attrs.output ||
|
|
274
|
+
attrs['output.value'] ||
|
|
275
|
+
attrs['gen_ai.task.output'] ||
|
|
276
|
+
span.statusMessage ||
|
|
277
|
+
'';
|
|
278
|
+
|
|
279
|
+
const toolError =
|
|
280
|
+
span.statusCode === 'ERROR' || span.statusCode === 'STATUS_CODE_ERROR'
|
|
281
|
+
? (span.statusMessage || attrs.error || attrs['exception.message'] || 'Tool execution failed')
|
|
282
|
+
: (attrs.error || null);
|
|
283
|
+
|
|
284
|
+
toolCalls.push({
|
|
285
|
+
name: toolName,
|
|
286
|
+
arguments: toolArgs,
|
|
287
|
+
durationMs: durMs,
|
|
288
|
+
status: isError ? 'ERROR' : 'OK',
|
|
289
|
+
result: typeof toolResultRaw === 'object' ? JSON.stringify(toolResultRaw) : String(toolResultRaw),
|
|
290
|
+
error: toolError ? String(toolError) : null,
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// 提炼异常
|
|
295
|
+
if (isError) {
|
|
296
|
+
const errMsg =
|
|
297
|
+
span.statusMessage ||
|
|
298
|
+
attrs['exception.message'] ||
|
|
299
|
+
attrs['exception.stacktrace'] ||
|
|
300
|
+
attrs.error;
|
|
301
|
+
if (errMsg) {
|
|
302
|
+
const str = String(errMsg).trim();
|
|
303
|
+
if (!errors.includes(str)) errors.push(str);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
if (totalDurationMs === 0 && spans.length > 0) {
|
|
309
|
+
const maxDur = Math.max(...spans.map((s) => (s.duration ? Math.round(Number(s.duration) / 1_000_000) : 0)));
|
|
310
|
+
totalDurationMs = maxDur;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
return {
|
|
314
|
+
traceId,
|
|
315
|
+
status: overallStatus,
|
|
316
|
+
durationMs: totalDurationMs,
|
|
317
|
+
thoughts,
|
|
318
|
+
toolCalls,
|
|
319
|
+
errors,
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function renderSummaryMarkdown(summary) {
|
|
324
|
+
const lines = [
|
|
325
|
+
`# Trace Summary: ${summary.traceId}`,
|
|
326
|
+
`- **Status**: ${summary.status}`,
|
|
327
|
+
`- **Duration**: ${summary.durationMs}ms`,
|
|
328
|
+
'',
|
|
329
|
+
'## Thoughts (CoT)',
|
|
330
|
+
];
|
|
331
|
+
|
|
332
|
+
if (summary.thoughts.length === 0) {
|
|
333
|
+
lines.push('_No thought/reasoning spans recorded._');
|
|
334
|
+
} else {
|
|
335
|
+
for (const t of summary.thoughts) {
|
|
336
|
+
lines.push(`> ${t.replace(/\n/g, '\n> ')}`);
|
|
337
|
+
lines.push('');
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
lines.push('');
|
|
342
|
+
lines.push('## Tool Invocations');
|
|
343
|
+
if (summary.toolCalls.length === 0) {
|
|
344
|
+
lines.push('_No tool invocations recorded._');
|
|
345
|
+
} else {
|
|
346
|
+
summary.toolCalls.forEach((tc, idx) => {
|
|
347
|
+
lines.push(`### ${idx + 1}. \`${tc.name}\` (${tc.durationMs}ms) - [${tc.status}]`);
|
|
348
|
+
lines.push(`- **Arguments**: \`${typeof tc.arguments === 'object' ? JSON.stringify(tc.arguments) : tc.arguments}\``);
|
|
349
|
+
if (tc.result) {
|
|
350
|
+
const resPreview = tc.result.length > 500 ? tc.result.slice(0, 500) + '...' : tc.result;
|
|
351
|
+
lines.push(`- **Result**: \`${resPreview}\``);
|
|
352
|
+
}
|
|
353
|
+
if (tc.error) {
|
|
354
|
+
lines.push(`- **Error**: ${tc.error}`);
|
|
355
|
+
}
|
|
356
|
+
lines.push('');
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
lines.push('## Errors');
|
|
361
|
+
if (summary.errors.length === 0) {
|
|
362
|
+
lines.push('_No errors recorded._');
|
|
363
|
+
} else {
|
|
364
|
+
for (const err of summary.errors) {
|
|
365
|
+
lines.push(`- ${err}`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
return lines.join('\n');
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function renderSummaryText(summary) {
|
|
373
|
+
return renderSummaryMarkdown(summary);
|
|
374
|
+
}
|
|
375
|
+
|
|
138
376
|
// 一个模块导出三个 topic:registry 展开后各自独立
|
|
139
377
|
module.exports = traceTopic;
|
|
140
378
|
module.exports.extraTopics = [obsTopic, scoreTopic];
|
|
379
|
+
module.exports.analyzeTraceSpans = analyzeTraceSpans;
|
|
380
|
+
module.exports.renderSummaryMarkdown = renderSummaryMarkdown;
|
|
381
|
+
module.exports.renderSummaryText = renderSummaryText;
|
package/lib/commands/skill.js
CHANGED
|
@@ -327,15 +327,137 @@ const install = {
|
|
|
327
327
|
},
|
|
328
328
|
};
|
|
329
329
|
|
|
330
|
+
const upgrade = {
|
|
331
|
+
name: 'upgrade',
|
|
332
|
+
summary: '原地升级已有技能(上传 zip 或目录覆盖并可选自动发版)',
|
|
333
|
+
args: [
|
|
334
|
+
{ name: 'id', required: true, summary: '技能 ID' },
|
|
335
|
+
{ name: 'file', required: true, summary: '新版 zip 文件路径或技能目录' },
|
|
336
|
+
],
|
|
337
|
+
flags: {
|
|
338
|
+
publish: { type: 'boolean', summary: '升级后是否自动发布新版本(缺省 true)', default: true },
|
|
339
|
+
'no-publish': { type: 'boolean', summary: '升级后不自动发布新版本' },
|
|
340
|
+
'change-log': { type: 'string', summary: '版本发布更新说明' },
|
|
341
|
+
remark: { type: 'string', summary: '版本发布更新说明(等同 --change-log)' },
|
|
342
|
+
},
|
|
343
|
+
examples: [
|
|
344
|
+
'wd-cli skill upgrade 123 ./new-skill.zip',
|
|
345
|
+
'wd-cli skill upgrade 123 ./my-skill-dir/ --change-log "升级工具函数"',
|
|
346
|
+
'wd-cli skill upgrade 123 ./my-skill-dir/ --remark "升级工具函数"',
|
|
347
|
+
'wd-cli skill upgrade 123 ./new-skill.zip --no-publish',
|
|
348
|
+
],
|
|
349
|
+
async run(ctx) {
|
|
350
|
+
const id = encodeURIComponent(ctx.args[0]);
|
|
351
|
+
const inputPath = ctx.args[1];
|
|
352
|
+
if (!fs.existsSync(inputPath)) {
|
|
353
|
+
throw new CliError(`路径不存在:${inputPath}`, EXIT.USAGE);
|
|
354
|
+
}
|
|
355
|
+
let zipPath = inputPath;
|
|
356
|
+
let cleanup = null;
|
|
357
|
+
if (fs.statSync(inputPath).isDirectory()) {
|
|
358
|
+
if (!fs.existsSync(path.join(inputPath, 'SKILL.md'))) {
|
|
359
|
+
throw new CliError(`目录中未包含 SKILL.md 文件:${inputPath}`, EXIT.USAGE);
|
|
360
|
+
}
|
|
361
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-cli-skill-upgrade-'));
|
|
362
|
+
zipPath = path.join(tmpDir, 'skill.zip');
|
|
363
|
+
cleanup = () => fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
364
|
+
try {
|
|
365
|
+
await execFileAsync('zip', ['-r', '-q', zipPath, '.'], { cwd: inputPath });
|
|
366
|
+
} catch (err) {
|
|
367
|
+
if (cleanup) cleanup();
|
|
368
|
+
throw new CliError(`打包 zip 失败:${err.message}`, EXIT.BUSINESS);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
try {
|
|
373
|
+
const shouldPublish = ctx.flags['no-publish'] ? false : (ctx.flags.publish !== false);
|
|
374
|
+
const effectiveChangeLog = ctx.flags.changeLog || ctx.flags.remark;
|
|
375
|
+
const form = http.buildFormData(
|
|
376
|
+
{
|
|
377
|
+
publish: String(shouldPublish),
|
|
378
|
+
changeLog: effectiveChangeLog,
|
|
379
|
+
},
|
|
380
|
+
[{ name: 'file', path: zipPath }]
|
|
381
|
+
);
|
|
382
|
+
const res = await http.request(ctx, {
|
|
383
|
+
method: 'POST',
|
|
384
|
+
path: `/skills/${id}/upgrade`,
|
|
385
|
+
form,
|
|
386
|
+
});
|
|
387
|
+
output.print(res, { flags: ctx.flags });
|
|
388
|
+
output.success(`技能 ${id} 已成功原地升级${shouldPublish ? '并发布新版本' : ''}`, ctx.flags);
|
|
389
|
+
return EXIT.OK;
|
|
390
|
+
} finally {
|
|
391
|
+
if (cleanup) cleanup();
|
|
392
|
+
}
|
|
393
|
+
},
|
|
394
|
+
};
|
|
395
|
+
|
|
396
|
+
const updateFile = {
|
|
397
|
+
name: 'update-file',
|
|
398
|
+
summary: '原地更新技能中的单个文件内容(如 SKILL.md)',
|
|
399
|
+
args: [{ name: 'id', required: true, summary: '技能 ID' }],
|
|
400
|
+
flags: {
|
|
401
|
+
path: { type: 'string', summary: '技能内的相对文件路径(如 SKILL.md,缺省 SKILL.md)' },
|
|
402
|
+
content: { type: 'string', summary: '文件文本内容' },
|
|
403
|
+
text: { type: 'string', summary: '文件文本内容(等同 --content)' },
|
|
404
|
+
file: { type: 'string', summary: '从本地文件或标准输入(-)读取内容' },
|
|
405
|
+
publish: { type: 'boolean', summary: '修改后是否自动发布新版本(缺省 true,可用 --no-publish 关闭)' },
|
|
406
|
+
'change-log': { type: 'string', summary: '自动发布的变更说明' },
|
|
407
|
+
remark: { type: 'string', summary: '自动发布的变更说明(等同 --change-log)' },
|
|
408
|
+
},
|
|
409
|
+
examples: [
|
|
410
|
+
'wd-cli skill update-file 123 --path SKILL.md --content "# New Skill"',
|
|
411
|
+
'wd-cli skill update-file 123 --path SKILL.md --text "# New Skill"',
|
|
412
|
+
'wd-cli skill update-file 123 --path SKILL.md --file ./local-SKILL.md',
|
|
413
|
+
'wd-cli skill update-file 123 --path SKILL.md --file ./local-SKILL.md --no-publish',
|
|
414
|
+
],
|
|
415
|
+
async run(ctx) {
|
|
416
|
+
const id = encodeURIComponent(ctx.args[0]);
|
|
417
|
+
const { content, text, file, publish, changeLog, remark } = ctx.flags;
|
|
418
|
+
const filePath = ctx.flags.path || 'SKILL.md';
|
|
419
|
+
let bodyText = content !== undefined ? content : text;
|
|
420
|
+
if (file !== undefined) {
|
|
421
|
+
bodyText = String(dataInput.readDataText(file, '--file'));
|
|
422
|
+
}
|
|
423
|
+
if (bodyText === undefined) {
|
|
424
|
+
throw new CliError('必须通过 --content, --text 或 --file 指定更新内容', EXIT.USAGE);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const shouldPublish = publish !== false && !ctx.flags.noPublish && !ctx.flags['no-publish'];
|
|
428
|
+
const effectiveChangeLog = changeLog || remark;
|
|
429
|
+
|
|
430
|
+
const query = {
|
|
431
|
+
path: filePath,
|
|
432
|
+
publish: String(shouldPublish),
|
|
433
|
+
};
|
|
434
|
+
if (effectiveChangeLog) {
|
|
435
|
+
query.changeLog = effectiveChangeLog;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
const res = await http.request(ctx, {
|
|
439
|
+
method: 'PUT',
|
|
440
|
+
path: `/skills/${id}/content`,
|
|
441
|
+
query,
|
|
442
|
+
headers: { 'Content-Type': 'text/plain' },
|
|
443
|
+
body: bodyText,
|
|
444
|
+
});
|
|
445
|
+
output.print(res, { flags: ctx.flags });
|
|
446
|
+
output.success(`技能 ${id} 的文件 ${filePath} 已更新${shouldPublish ? '并发布新版本' : ''}`, ctx.flags);
|
|
447
|
+
return EXIT.OK;
|
|
448
|
+
},
|
|
449
|
+
};
|
|
450
|
+
|
|
330
451
|
module.exports = {
|
|
331
452
|
id: 'skill',
|
|
332
|
-
summary: '技能:列出 / 搜索 / 下载 / 安装 / 上传',
|
|
453
|
+
summary: '技能:列出 / 搜索 / 下载 / 安装 / 上传 / 原地升级',
|
|
333
454
|
description: '安装目录与 @dmall-inc/skills-cli 一致;令牌直连模式下需要 wat_ 工作空间令牌。',
|
|
334
455
|
principals: ['workspace'],
|
|
335
|
-
commands: [list, search, versions, download, importCmd, install],
|
|
456
|
+
commands: [list, search, versions, download, importCmd, install, upgrade, updateFile],
|
|
336
457
|
parseSkillRef,
|
|
337
458
|
resolveTargets,
|
|
338
459
|
backupExisting,
|
|
339
460
|
locateSkillRoot,
|
|
340
461
|
INSTALL_TARGETS,
|
|
341
462
|
};
|
|
463
|
+
|
package/lib/http.js
CHANGED
|
@@ -199,7 +199,7 @@ async function request(ctx, { method = 'GET', base, path: pathname, query, body,
|
|
|
199
199
|
if (form) {
|
|
200
200
|
init.body = form; // FormData:让 fetch 自己带 boundary
|
|
201
201
|
} else if (body !== undefined && body !== null) {
|
|
202
|
-
headers['Content-Type'] = 'application/json';
|
|
202
|
+
headers['Content-Type'] = headers['Content-Type'] || 'application/json';
|
|
203
203
|
init.body = typeof body === 'string' ? body : JSON.stringify(body);
|
|
204
204
|
}
|
|
205
205
|
return fetchWithTimeout(url, init, ctx.timeoutMs, ctx);
|
|
@@ -210,6 +210,9 @@ async function request(ctx, { method = 'GET', base, path: pathname, query, body,
|
|
|
210
210
|
const refreshed = await ctx.ensureFreshToken(true).catch(() => false);
|
|
211
211
|
if (refreshed) response = await send();
|
|
212
212
|
}
|
|
213
|
+
if (typeof onResponse === 'function') {
|
|
214
|
+
try { onResponse(response); } catch {}
|
|
215
|
+
}
|
|
213
216
|
|
|
214
217
|
const text = await response.text();
|
|
215
218
|
if (raw) {
|
|
@@ -304,7 +307,7 @@ function parseFilename(disposition) {
|
|
|
304
307
|
* 消费 SSE 流。onEvent 收到 { event, data }(data 为已 JSON.parse 的对象,解析失败给原始串)。
|
|
305
308
|
* 用于 AG-UI 事件流:文本增量、结束、错误。
|
|
306
309
|
*/
|
|
307
|
-
async function stream(ctx, { method = 'POST', base, path: pathname, query, body, onEvent, timeoutMs }) {
|
|
310
|
+
async function stream(ctx, { method = 'POST', base, path: pathname, query, body, onEvent, onResponse, timeoutMs }) {
|
|
308
311
|
const url = buildUrl(base ?? ctx.chatBase(), pathname, query);
|
|
309
312
|
const headers = await ctx.headers({ Accept: 'text/event-stream', 'Content-Type': 'application/json' });
|
|
310
313
|
const controller = new AbortController();
|
|
@@ -322,6 +325,9 @@ async function stream(ctx, { method = 'POST', base, path: pathname, query, body,
|
|
|
322
325
|
const text = await response.text().catch(() => '');
|
|
323
326
|
throw toCliError(response.status, safeJson(text), text, url);
|
|
324
327
|
}
|
|
328
|
+
if (typeof onResponse === 'function') {
|
|
329
|
+
try { onResponse(response); } catch {}
|
|
330
|
+
}
|
|
325
331
|
const decoder = new TextDecoder();
|
|
326
332
|
let buffer = '';
|
|
327
333
|
for await (const chunk of response.body) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dmall-inc/wd-cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Waterdrop platform CLI: sign in with your unified identity, pick a workspace, and use the open platform resources from your terminal",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "commonjs",
|