@dmall-inc/wd-cli 0.2.0 → 0.4.1
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 +88 -0
- package/docs/design-references.md +2 -0
- package/lib/args.js +2 -1
- package/lib/auth.js +1 -1
- package/lib/commands/auth.js +3 -3
- package/lib/commands/config.js +1 -0
- package/lib/commands/daemon.js +411 -0
- package/lib/commands/device.js +92 -0
- package/lib/commands/diwork.js +544 -0
- package/lib/commands/help.js +1 -0
- package/lib/commands/index.js +5 -0
- package/lib/commands/open.js +89 -0
- package/lib/commands/tool.js +327 -0
- package/lib/config.js +2 -1
- package/lib/daemon/agui.js +63 -0
- package/lib/daemon/channel.js +183 -0
- package/lib/daemon/enroll.js +91 -0
- package/lib/daemon/executors/acp.js +480 -0
- package/lib/daemon/executors/pi-approval-extension.ts +57 -0
- package/lib/daemon/executors/pi.js +360 -0
- package/lib/daemon/index.js +146 -0
- package/lib/daemon/jsonrpc.js +127 -0
- package/lib/daemon/permission.js +96 -0
- package/lib/daemon/roots.js +161 -0
- package/lib/daemon/runtimes.js +238 -0
- package/lib/daemon/service.js +135 -0
- package/lib/daemon/state.js +188 -0
- package/lib/daemon/supervisor.js +244 -0
- package/package.json +1 -1
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* DiWork(/api/open/diwork/**):以登录用户本人身份使用自己的 DiWork(AI 数字员工)——
|
|
5
|
+
* 运行环境探测、单轮调用、工作区文件管理、自动化任务管理。
|
|
6
|
+
*
|
|
7
|
+
* 这些端点在 server 进程(DiWork 文件落在 server 与 Pod 共享的存储卷上),所以和 `agent chat`
|
|
8
|
+
* 一样走 ctx.chatBase():单入口部署零配置,拆分部署在 profile 里配 chatBaseUrl 指向 server。
|
|
9
|
+
* 只接受用户登录态——DiWork 的一切都按「本人」隔离,令牌直连没有对应的身份。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const fs = require('node:fs');
|
|
13
|
+
const path = require('node:path');
|
|
14
|
+
|
|
15
|
+
const http = require('../http');
|
|
16
|
+
const dataInput = require('../data');
|
|
17
|
+
const output = require('../output');
|
|
18
|
+
const { CliError, EXIT } = output;
|
|
19
|
+
|
|
20
|
+
/** 服务端执行超时缺省 300s、上限 600s;HTTP 等待在有效超时上多留 30s。 */
|
|
21
|
+
const CHAT_DEFAULT_TIMEOUT_MS = 300_000;
|
|
22
|
+
const CHAT_MIN_TIMEOUT_MS = 10_000;
|
|
23
|
+
const CHAT_MAX_TIMEOUT_MS = 600_000;
|
|
24
|
+
const CHAT_HTTP_MARGIN_MS = 30_000;
|
|
25
|
+
const DEFAULT_WAIT_MS = 180_000;
|
|
26
|
+
const POLL_INTERVAL_MS = 3_000;
|
|
27
|
+
|
|
28
|
+
const FILE_COLUMNS = [
|
|
29
|
+
{ key: 'type', label: '类型' },
|
|
30
|
+
{ key: 'name', label: '名称' },
|
|
31
|
+
{ key: 'size', label: '大小' },
|
|
32
|
+
{ key: 'modified', label: '修改时间' },
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
const AUTOMATION_COLUMNS = [
|
|
36
|
+
{ key: 'id', label: 'ID' },
|
|
37
|
+
{ key: 'name', label: '名称' },
|
|
38
|
+
{ key: 'scheduleType', label: '方式' },
|
|
39
|
+
{ key: 'cronExpression', label: 'Cron' },
|
|
40
|
+
{ key: 'enabled', label: '启用' },
|
|
41
|
+
{ key: 'nextRunAt', label: '下次执行' },
|
|
42
|
+
{ key: 'lastRunAt', label: '上次执行' },
|
|
43
|
+
];
|
|
44
|
+
|
|
45
|
+
const EXECUTION_COLUMNS = [
|
|
46
|
+
{ key: 'id', label: 'ID' },
|
|
47
|
+
{ key: 'status', label: '状态' },
|
|
48
|
+
{ key: 'triggerTime', label: '触发时间' },
|
|
49
|
+
{ key: 'durationMs', label: '耗时(ms)' },
|
|
50
|
+
{ key: 'errorMessage', label: '错误' },
|
|
51
|
+
];
|
|
52
|
+
|
|
53
|
+
/** 测试可替换的等待函数(轮询供给)。 */
|
|
54
|
+
const timers = { sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)) };
|
|
55
|
+
|
|
56
|
+
/** 全部请求打对话基址(server)。 */
|
|
57
|
+
function req(ctx, options) {
|
|
58
|
+
return http.request(ctx, { base: ctx.chatBase(), ...options });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function wantsJson(flags) {
|
|
62
|
+
return output.resolveFormat(flags) !== 'table' || Boolean(flags.json || flags.jq);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function readJsonObjectFile(value, label) {
|
|
66
|
+
let raw;
|
|
67
|
+
if (String(value) === '-') {
|
|
68
|
+
raw = dataInput.readStdin();
|
|
69
|
+
} else {
|
|
70
|
+
if (!fs.existsSync(value)) throw new CliError(`${label} 指定的文件不存在:${value}`, EXIT.USAGE);
|
|
71
|
+
raw = fs.readFileSync(value, 'utf8');
|
|
72
|
+
}
|
|
73
|
+
let parsed;
|
|
74
|
+
try {
|
|
75
|
+
parsed = JSON.parse(raw);
|
|
76
|
+
} catch (error) {
|
|
77
|
+
throw new CliError(`${label} 不是合法 JSON:${error.message}`, EXIT.USAGE);
|
|
78
|
+
}
|
|
79
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
80
|
+
throw new CliError(`${label} 须为 JSON 对象`, EXIT.USAGE);
|
|
81
|
+
}
|
|
82
|
+
return parsed;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function humanSize(bytes) {
|
|
86
|
+
if (typeof bytes !== 'number') return '';
|
|
87
|
+
if (bytes < 1024) return `${bytes}B`;
|
|
88
|
+
const units = ['KB', 'MB', 'GB'];
|
|
89
|
+
let v = bytes / 1024;
|
|
90
|
+
let i = 0;
|
|
91
|
+
while (v >= 1024 && i < units.length - 1) {
|
|
92
|
+
v /= 1024;
|
|
93
|
+
i += 1;
|
|
94
|
+
}
|
|
95
|
+
return `${v.toFixed(v >= 10 ? 0 : 1)}${units[i]}`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function formatTime(ms) {
|
|
99
|
+
if (typeof ms !== 'number') return '';
|
|
100
|
+
const d = new Date(ms);
|
|
101
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
102
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function clampChatTimeout(value) {
|
|
106
|
+
const v = Number(value) > 0 ? Number(value) : CHAT_DEFAULT_TIMEOUT_MS;
|
|
107
|
+
return Math.max(CHAT_MIN_TIMEOUT_MS, Math.min(CHAT_MAX_TIMEOUT_MS, v));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ==================== 运行环境与调用 ====================
|
|
111
|
+
|
|
112
|
+
const status = {
|
|
113
|
+
name: 'status',
|
|
114
|
+
summary: '查看 DiWork 运行环境状态(缺省只读探测,--ensure 触发供给)',
|
|
115
|
+
flags: {
|
|
116
|
+
ensure: { type: 'boolean', summary: '未就绪时触发供给(会为你创建运行环境)' },
|
|
117
|
+
retry: { type: 'boolean', summary: '供给失败后重新供给(隐含 --ensure)' },
|
|
118
|
+
},
|
|
119
|
+
examples: ['wd-cli diwork status', 'wd-cli diwork status --ensure', 'wd-cli diwork status --retry'],
|
|
120
|
+
async run(ctx) {
|
|
121
|
+
const ensure = Boolean(ctx.flags.ensure || ctx.flags.retry);
|
|
122
|
+
const query = ensure ? { retry: ctx.flags.retry ? 'true' : undefined } : { probe: 'true' };
|
|
123
|
+
const view = (await req(ctx, { path: '/diwork/runtime', query })) || {};
|
|
124
|
+
if (wantsJson(ctx.flags)) {
|
|
125
|
+
output.print(view, { flags: ctx.flags });
|
|
126
|
+
} else {
|
|
127
|
+
const rows = [
|
|
128
|
+
{ key: '状态', value: view.status || '' },
|
|
129
|
+
{ key: '超级 Agent', value: view.superAgentName || (view.superAgentId ? String(view.superAgentId) : '') },
|
|
130
|
+
];
|
|
131
|
+
if (view.errorMessage) rows.push({ key: '失败原因', value: view.errorMessage });
|
|
132
|
+
output.print(rows, {
|
|
133
|
+
flags: ctx.flags,
|
|
134
|
+
columns: [
|
|
135
|
+
{ key: 'key', label: '项' },
|
|
136
|
+
{ key: 'value', label: '值' },
|
|
137
|
+
],
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
if (view.status === 'DISABLED') {
|
|
141
|
+
throw new CliError('DiWork 未启用', EXIT.BUSINESS, { hint: '请联系平台管理员开通' });
|
|
142
|
+
}
|
|
143
|
+
if (view.status === 'FAILED') {
|
|
144
|
+
throw new CliError(view.errorMessage || '运行环境供给失败', EXIT.BUSINESS, {
|
|
145
|
+
hint: '执行 wd-cli diwork status --retry 重新供给',
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
return EXIT.OK;
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const chat = {
|
|
153
|
+
name: 'chat',
|
|
154
|
+
summary: '让你的 DiWork 执行一轮任务并返回回复',
|
|
155
|
+
flags: {
|
|
156
|
+
message: { type: 'string', short: 'm', summary: '消息内容;- 表示从标准输入读(必填)' },
|
|
157
|
+
'session-id': { type: 'string', summary: '接着已有 DiWork 会话聊;缺省新建(Web 端会话列表可见)' },
|
|
158
|
+
'wait-ms': { type: 'number', summary: `运行环境供给中时的最长等待(缺省 ${DEFAULT_WAIT_MS})` },
|
|
159
|
+
},
|
|
160
|
+
examples: [
|
|
161
|
+
'wd-cli diwork chat -m "把今天的销售日报整理成表格"',
|
|
162
|
+
'wd-cli diwork chat -m "继续" --session-id 0b6f…',
|
|
163
|
+
'cat task.md | wd-cli diwork chat -m - -o json',
|
|
164
|
+
'wd-cli diwork chat -m "跑一下周报" --timeout-ms 600000',
|
|
165
|
+
],
|
|
166
|
+
async run(ctx) {
|
|
167
|
+
if (ctx.flags.message === undefined) {
|
|
168
|
+
throw new CliError('缺少 --message', EXIT.USAGE, { hint: '例:wd-cli diwork chat -m "整理日报";-m - 从标准输入读' });
|
|
169
|
+
}
|
|
170
|
+
const message = String(dataInput.readDataText(ctx.flags.message, '--message')).trim();
|
|
171
|
+
if (!message) throw new CliError('消息内容为空', EXIT.USAGE);
|
|
172
|
+
|
|
173
|
+
const timeoutMs = clampChatTimeout(ctx.flags.timeoutMs);
|
|
174
|
+
const body = { message, timeoutMs };
|
|
175
|
+
if (ctx.flags.sessionId) body.sessionId = String(ctx.flags.sessionId);
|
|
176
|
+
// --timeout-ms 语义是执行超时;HTTP 等待多留余量
|
|
177
|
+
ctx.flags.timeoutMs = timeoutMs + CHAT_HTTP_MARGIN_MS;
|
|
178
|
+
|
|
179
|
+
const waitMs = Number(ctx.flags.waitMs) >= 0 && ctx.flags.waitMs !== undefined ? Number(ctx.flags.waitMs) : DEFAULT_WAIT_MS;
|
|
180
|
+
const deadline = Date.now() + waitMs;
|
|
181
|
+
let result;
|
|
182
|
+
let announced = false;
|
|
183
|
+
for (;;) {
|
|
184
|
+
result = (await req(ctx, { method: 'POST', path: '/diwork/chat', body })) || {};
|
|
185
|
+
if (result.ready !== false) break;
|
|
186
|
+
if (Date.now() >= deadline) {
|
|
187
|
+
throw new CliError(`DiWork 运行环境未在 ${Math.round(waitMs / 1000)} 秒内就绪(当前 ${result.status || '未知'})`, EXIT.BUSINESS, {
|
|
188
|
+
hint: '稍后重试,或加大 --wait-ms;wd-cli diwork status 查看状态',
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
if (!announced) {
|
|
192
|
+
output.info(`DiWork 运行环境准备中(${result.status || 'PROVISIONING'}),等待就绪…`, ctx.flags);
|
|
193
|
+
announced = true;
|
|
194
|
+
}
|
|
195
|
+
await timers.sleep(Math.min(POLL_INTERVAL_MS, Math.max(0, deadline - Date.now())));
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const ok = result.status === 'SUCCESS';
|
|
199
|
+
if (wantsJson(ctx.flags)) {
|
|
200
|
+
output.print(result, { flags: ctx.flags });
|
|
201
|
+
} else if (ok) {
|
|
202
|
+
output.print(result.text || '', { flags: ctx.flags });
|
|
203
|
+
}
|
|
204
|
+
if (result.sessionId && !ctx.flags.sessionId) {
|
|
205
|
+
output.info(`会话 id:${result.sessionId}(加 --session-id ${result.sessionId} 可接着聊)`, ctx.flags);
|
|
206
|
+
}
|
|
207
|
+
if (!ok) {
|
|
208
|
+
throw new CliError(result.errorMessage || `执行未成功(${result.status || '未知状态'})`, EXIT.BUSINESS, {
|
|
209
|
+
hint: result.status === 'TIMEOUT' ? '可加大 --timeout-ms(上限 600000)' : undefined,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
return EXIT.OK;
|
|
213
|
+
},
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
// ==================== 工作区文件 ====================
|
|
217
|
+
|
|
218
|
+
const fileLs = {
|
|
219
|
+
name: 'file ls',
|
|
220
|
+
summary: '列出工作区目录(缺省根目录)',
|
|
221
|
+
args: [{ name: 'path', summary: '目录路径(相对工作区根)' }],
|
|
222
|
+
examples: ['wd-cli diwork file ls', 'wd-cli diwork file ls reports/2026'],
|
|
223
|
+
async run(ctx) {
|
|
224
|
+
const result = (await req(ctx, { path: '/diwork/files/list', query: { path: ctx.args[0] } })) || [];
|
|
225
|
+
if (wantsJson(ctx.flags)) {
|
|
226
|
+
output.print(result, { flags: ctx.flags });
|
|
227
|
+
return EXIT.OK;
|
|
228
|
+
}
|
|
229
|
+
const rows = (Array.isArray(result) ? result : []).map((e) => {
|
|
230
|
+
const isDir = String(e.type || '').toUpperCase() === 'DIR';
|
|
231
|
+
return {
|
|
232
|
+
type: isDir ? '目录' : '文件',
|
|
233
|
+
name: isDir ? `${e.name}/` : e.name,
|
|
234
|
+
size: isDir ? '' : humanSize(e.size),
|
|
235
|
+
modified: formatTime(e.modifiedAt),
|
|
236
|
+
};
|
|
237
|
+
});
|
|
238
|
+
output.print(rows, { flags: ctx.flags, columns: FILE_COLUMNS, empty: '目录为空' });
|
|
239
|
+
return EXIT.OK;
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
const fileTree = {
|
|
244
|
+
name: 'file tree',
|
|
245
|
+
summary: '查看工作区目录树',
|
|
246
|
+
examples: ['wd-cli diwork file tree -o json'],
|
|
247
|
+
async run(ctx) {
|
|
248
|
+
output.print(await req(ctx, { path: '/diwork/files/tree' }), { flags: ctx.flags });
|
|
249
|
+
return EXIT.OK;
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
const fileDownload = {
|
|
254
|
+
name: 'file download',
|
|
255
|
+
summary: '下载工作区文件',
|
|
256
|
+
args: [{ name: 'path', required: true, summary: '文件路径(相对工作区根)' }],
|
|
257
|
+
flags: { out: { type: 'string', short: 'O', summary: '输出文件或目录,- 表示标准输出' } },
|
|
258
|
+
examples: ['wd-cli diwork file download reports/日报.xlsx', 'wd-cli diwork file download a.md -O -'],
|
|
259
|
+
async run(ctx) {
|
|
260
|
+
const saved = await http.download(ctx, {
|
|
261
|
+
base: ctx.chatBase(),
|
|
262
|
+
path: '/diwork/files/download',
|
|
263
|
+
query: { path: ctx.args[0] },
|
|
264
|
+
outPath: ctx.flags.out,
|
|
265
|
+
defaultName: path.basename(ctx.args[0]),
|
|
266
|
+
});
|
|
267
|
+
if (saved.path !== '-') output.success(`已下载:${saved.path}(${saved.bytes} 字节)`, ctx.flags);
|
|
268
|
+
return EXIT.OK;
|
|
269
|
+
},
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const fileUpload = {
|
|
273
|
+
name: 'file upload',
|
|
274
|
+
summary: '上传一个或多个本地文件到工作区(同名覆盖)',
|
|
275
|
+
args: [{ name: 'file...', required: true, summary: '本地文件路径,可多个' }],
|
|
276
|
+
flags: { path: { type: 'string', summary: '目标目录(相对工作区根,缺省根目录)' } },
|
|
277
|
+
examples: ['wd-cli diwork file upload ./data.csv', 'wd-cli diwork file upload a.pdf b.pdf --path inbox'],
|
|
278
|
+
async run(ctx) {
|
|
279
|
+
const files = ctx.args;
|
|
280
|
+
// 先整体校验再发请求:传到一半才发现某个路径写错最难收拾
|
|
281
|
+
for (const file of files) {
|
|
282
|
+
if (!fs.existsSync(file)) throw new CliError(`本地文件不存在:${file}`, EXIT.USAGE);
|
|
283
|
+
if (fs.statSync(file).isDirectory()) {
|
|
284
|
+
throw new CliError(`不支持上传目录:${file}`, EXIT.USAGE, { hint: '逐个指定文件,或先打包成 zip' });
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
const results = [];
|
|
288
|
+
let failed = 0;
|
|
289
|
+
for (const file of files) {
|
|
290
|
+
try {
|
|
291
|
+
const form = http.buildFormData({ path: ctx.flags.path }, [{ name: 'file', path: file }]);
|
|
292
|
+
const entry = await req(ctx, { method: 'POST', path: '/diwork/files/upload', form });
|
|
293
|
+
results.push({ file, status: 'ok', path: entry && entry.path });
|
|
294
|
+
} catch (error) {
|
|
295
|
+
failed += 1;
|
|
296
|
+
results.push({ file, status: 'failed', error: error.message });
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
output.print(results, {
|
|
300
|
+
flags: ctx.flags,
|
|
301
|
+
columns: [
|
|
302
|
+
{ key: 'file', label: '本地文件' },
|
|
303
|
+
{ key: 'status', label: '结果' },
|
|
304
|
+
{ key: 'path', label: '工作区路径' },
|
|
305
|
+
{ key: 'error', label: '错误' },
|
|
306
|
+
],
|
|
307
|
+
});
|
|
308
|
+
return failed > 0 ? EXIT.BUSINESS : EXIT.OK;
|
|
309
|
+
},
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
const fileMkdir = {
|
|
313
|
+
name: 'file mkdir',
|
|
314
|
+
summary: '新建目录',
|
|
315
|
+
args: [{ name: 'path', required: true, summary: '目录路径(相对工作区根)' }],
|
|
316
|
+
examples: ['wd-cli diwork file mkdir reports/2026'],
|
|
317
|
+
async run(ctx) {
|
|
318
|
+
await req(ctx, { method: 'POST', path: '/diwork/files/mkdir', body: { path: ctx.args[0] } });
|
|
319
|
+
output.success(`已创建目录 ${ctx.args[0]}`, ctx.flags);
|
|
320
|
+
return EXIT.OK;
|
|
321
|
+
},
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
const fileRename = {
|
|
325
|
+
name: 'file rename',
|
|
326
|
+
summary: '重命名文件或目录(同目录内改名)',
|
|
327
|
+
args: [
|
|
328
|
+
{ name: 'path', required: true, summary: '原路径' },
|
|
329
|
+
{ name: 'newName', required: true, summary: '新名称(不含目录)' },
|
|
330
|
+
],
|
|
331
|
+
examples: ['wd-cli diwork file rename reports/draft.md final.md'],
|
|
332
|
+
async run(ctx) {
|
|
333
|
+
await req(ctx, { method: 'POST', path: '/diwork/files/rename', body: { path: ctx.args[0], newName: ctx.args[1] } });
|
|
334
|
+
output.success(`已重命名为 ${ctx.args[1]}`, ctx.flags);
|
|
335
|
+
return EXIT.OK;
|
|
336
|
+
},
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
const fileRm = {
|
|
340
|
+
name: 'file rm',
|
|
341
|
+
summary: '删除文件或目录(可多个)',
|
|
342
|
+
args: [{ name: 'path...', required: true, summary: '路径,可多个' }],
|
|
343
|
+
examples: ['wd-cli diwork file rm tmp/a.log tmp/b.log --yes'],
|
|
344
|
+
async run(ctx) {
|
|
345
|
+
const paths = ctx.args;
|
|
346
|
+
const ok = await dataInput.confirm(`确认删除 DiWork 工作区中的 ${paths.join('、')}?`, ctx.flags);
|
|
347
|
+
if (!ok) {
|
|
348
|
+
output.info('已取消', ctx.flags);
|
|
349
|
+
return EXIT.OK;
|
|
350
|
+
}
|
|
351
|
+
const results = (await req(ctx, { method: 'POST', path: '/diwork/files/batch-delete', body: { paths } })) || [];
|
|
352
|
+
const list = Array.isArray(results) ? results : [];
|
|
353
|
+
output.print(
|
|
354
|
+
wantsJson(ctx.flags) ? list : list.map((r) => ({ path: r.path, result: r.success ? 'ok' : 'failed', message: r.message || '' })),
|
|
355
|
+
{
|
|
356
|
+
flags: ctx.flags,
|
|
357
|
+
columns: [
|
|
358
|
+
{ key: 'path', label: '路径' },
|
|
359
|
+
{ key: 'result', label: '结果' },
|
|
360
|
+
{ key: 'message', label: '说明' },
|
|
361
|
+
],
|
|
362
|
+
}
|
|
363
|
+
);
|
|
364
|
+
return list.some((r) => !r.success) ? EXIT.BUSINESS : EXIT.OK;
|
|
365
|
+
},
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
// ==================== 自动化任务 ====================
|
|
369
|
+
|
|
370
|
+
const automationArg = { name: 'id', required: true, summary: '自动化任务 id' };
|
|
371
|
+
|
|
372
|
+
function automationPath(ctx, suffix = '') {
|
|
373
|
+
return `/diwork/automations/${encodeURIComponent(ctx.args[0])}${suffix}`;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
const automationList = {
|
|
377
|
+
name: 'automation list',
|
|
378
|
+
summary: '列出我的 DiWork 自动化任务',
|
|
379
|
+
examples: ['wd-cli diwork automation list'],
|
|
380
|
+
async run(ctx) {
|
|
381
|
+
const result = await req(ctx, { path: '/diwork/automations' });
|
|
382
|
+
output.print(result, { flags: ctx.flags, columns: AUTOMATION_COLUMNS, empty: '还没有自动化任务' });
|
|
383
|
+
return EXIT.OK;
|
|
384
|
+
},
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
const automationGet = {
|
|
388
|
+
name: 'automation get',
|
|
389
|
+
summary: '查看自动化任务详情',
|
|
390
|
+
args: [automationArg],
|
|
391
|
+
examples: ['wd-cli diwork automation get 12'],
|
|
392
|
+
async run(ctx) {
|
|
393
|
+
output.print(await req(ctx, { path: automationPath(ctx) }), { flags: ctx.flags });
|
|
394
|
+
return EXIT.OK;
|
|
395
|
+
},
|
|
396
|
+
};
|
|
397
|
+
|
|
398
|
+
const automationCreate = {
|
|
399
|
+
name: 'automation create',
|
|
400
|
+
summary: '从 JSON 文件创建自动化任务(字段同 Web 自动化页)',
|
|
401
|
+
flags: { file: { type: 'string', summary: '任务 JSON 文件路径,- 为标准输入(必填)' } },
|
|
402
|
+
examples: [
|
|
403
|
+
'wd-cli diwork automation create --file daily.json',
|
|
404
|
+
'echo \'{"name":"日报","scheduleType":"cron","cronExpression":"0 0 9 * * ?","params":"整理昨日销售日报"}\' | wd-cli diwork automation create --file -',
|
|
405
|
+
],
|
|
406
|
+
async run(ctx) {
|
|
407
|
+
if (ctx.flags.file === undefined) {
|
|
408
|
+
throw new CliError('缺少 --file', EXIT.USAGE, {
|
|
409
|
+
hint: '必填 name / scheduleType(cron|periodic|once);重复型给 cronExpression,单次给 runAt;params 为执行输入',
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
const body = readJsonObjectFile(ctx.flags.file, '--file');
|
|
413
|
+
const created = await req(ctx, { method: 'POST', path: '/diwork/automations', body });
|
|
414
|
+
if (wantsJson(ctx.flags)) {
|
|
415
|
+
output.print(created, { flags: ctx.flags });
|
|
416
|
+
} else {
|
|
417
|
+
output.success(`已创建自动化任务 ${created && created.id ? created.id : ''}`.trim(), ctx.flags);
|
|
418
|
+
}
|
|
419
|
+
return EXIT.OK;
|
|
420
|
+
},
|
|
421
|
+
};
|
|
422
|
+
|
|
423
|
+
const automationUpdate = {
|
|
424
|
+
name: 'automation update',
|
|
425
|
+
summary: '以 JSON 更新自动化任务(整体提交,字段同创建)',
|
|
426
|
+
args: [automationArg],
|
|
427
|
+
flags: { file: { type: 'string', summary: '任务 JSON 文件路径,- 为标准输入(必填)' } },
|
|
428
|
+
examples: ['wd-cli diwork automation get 12 -o json > t.json && vi t.json && wd-cli diwork automation update 12 --file t.json'],
|
|
429
|
+
async run(ctx) {
|
|
430
|
+
if (ctx.flags.file === undefined) throw new CliError('缺少 --file', EXIT.USAGE);
|
|
431
|
+
const body = readJsonObjectFile(ctx.flags.file, '--file');
|
|
432
|
+
const updated = await req(ctx, { method: 'PUT', path: automationPath(ctx), body });
|
|
433
|
+
if (wantsJson(ctx.flags)) output.print(updated, { flags: ctx.flags });
|
|
434
|
+
else output.success(`已更新自动化任务 ${ctx.args[0]}`, ctx.flags);
|
|
435
|
+
return EXIT.OK;
|
|
436
|
+
},
|
|
437
|
+
};
|
|
438
|
+
|
|
439
|
+
function toggle(name, action, verb) {
|
|
440
|
+
return {
|
|
441
|
+
name,
|
|
442
|
+
summary: `${verb}自动化任务`,
|
|
443
|
+
args: [automationArg],
|
|
444
|
+
examples: [`wd-cli diwork ${name} 12`],
|
|
445
|
+
async run(ctx) {
|
|
446
|
+
const result = await req(ctx, { method: 'POST', path: automationPath(ctx, `/${action}`) });
|
|
447
|
+
if (wantsJson(ctx.flags)) output.print(result, { flags: ctx.flags });
|
|
448
|
+
else output.success(`已${verb}自动化任务 ${ctx.args[0]}`, ctx.flags);
|
|
449
|
+
return EXIT.OK;
|
|
450
|
+
},
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const automationDelete = {
|
|
455
|
+
name: 'automation delete',
|
|
456
|
+
summary: '删除自动化任务',
|
|
457
|
+
args: [automationArg],
|
|
458
|
+
examples: ['wd-cli diwork automation delete 12 --yes'],
|
|
459
|
+
async run(ctx) {
|
|
460
|
+
const ok = await dataInput.confirm(`确认删除自动化任务 ${ctx.args[0]}?`, ctx.flags);
|
|
461
|
+
if (!ok) {
|
|
462
|
+
output.info('已取消', ctx.flags);
|
|
463
|
+
return EXIT.OK;
|
|
464
|
+
}
|
|
465
|
+
await req(ctx, { method: 'DELETE', path: automationPath(ctx) });
|
|
466
|
+
output.success('已删除', ctx.flags);
|
|
467
|
+
return EXIT.OK;
|
|
468
|
+
},
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
const automationRun = {
|
|
472
|
+
name: 'automation run',
|
|
473
|
+
summary: '立即执行一次自动化任务(在你的 DiWork 内运行,返回本次结果)',
|
|
474
|
+
args: [automationArg],
|
|
475
|
+
flags: { params: { type: 'string', summary: '本次执行输入(缺省用任务保存的 params)' } },
|
|
476
|
+
examples: ['wd-cli diwork automation run 12', 'wd-cli diwork automation run 12 --params "只看华东区"'],
|
|
477
|
+
async run(ctx) {
|
|
478
|
+
const body = ctx.flags.params !== undefined ? { params: String(ctx.flags.params) } : {};
|
|
479
|
+
// 立即执行要等 Pod 跑完:沿用对话的 HTTP 等待上限
|
|
480
|
+
if (!ctx.flags.timeoutMs) ctx.flags.timeoutMs = CHAT_MAX_TIMEOUT_MS + CHAT_HTTP_MARGIN_MS;
|
|
481
|
+
const result = (await req(ctx, { method: 'POST', path: automationPath(ctx, '/test-run'), body })) || {};
|
|
482
|
+
if (wantsJson(ctx.flags)) {
|
|
483
|
+
output.print(result, { flags: ctx.flags });
|
|
484
|
+
} else if (result.status === 'SUCCESS') {
|
|
485
|
+
output.print(result.resultSummary || '', { flags: ctx.flags });
|
|
486
|
+
}
|
|
487
|
+
if (result.status && result.status !== 'SUCCESS') {
|
|
488
|
+
throw new CliError(result.errorMessage || `执行未成功(${result.status})`, EXIT.BUSINESS);
|
|
489
|
+
}
|
|
490
|
+
return EXIT.OK;
|
|
491
|
+
},
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
const automationExecutions = {
|
|
495
|
+
name: 'automation executions',
|
|
496
|
+
summary: '查看自动化任务的执行历史(分页)',
|
|
497
|
+
args: [automationArg],
|
|
498
|
+
flags: {
|
|
499
|
+
page: { type: 'number', summary: '页码,从 1 开始' },
|
|
500
|
+
size: { type: 'number', summary: '每页条数' },
|
|
501
|
+
status: { type: 'string', summary: '按状态过滤:SUCCESS | FAILED | TIMEOUT | RUNNING' },
|
|
502
|
+
},
|
|
503
|
+
examples: ['wd-cli diwork automation executions 12', 'wd-cli diwork automation executions 12 --status FAILED --size 10'],
|
|
504
|
+
async run(ctx) {
|
|
505
|
+
const result = await req(ctx, {
|
|
506
|
+
path: automationPath(ctx, '/executions'),
|
|
507
|
+
query: { pageNum: ctx.flags.page, pageSize: ctx.flags.size, status: ctx.flags.status },
|
|
508
|
+
});
|
|
509
|
+
const rows = Array.isArray(result) ? result : result && result.list ? result.list : [];
|
|
510
|
+
output.print(wantsJson(ctx.flags) ? result : rows, { flags: ctx.flags, columns: EXECUTION_COLUMNS, empty: '暂无执行记录' });
|
|
511
|
+
return EXIT.OK;
|
|
512
|
+
},
|
|
513
|
+
};
|
|
514
|
+
|
|
515
|
+
module.exports = {
|
|
516
|
+
id: 'diwork',
|
|
517
|
+
summary: 'DiWork:运行环境 / 调用 / 工作区文件 / 自动化任务(本人)',
|
|
518
|
+
description:
|
|
519
|
+
'以登录用户本人身份操作自己的 DiWork(仅接受 wd-cli auth login 登录态)。chat 与 automation run 会在你的 DiWork 内真实执行任务;' +
|
|
520
|
+
'file rm、automation delete 不可恢复,需 --yes 确认。与 `automation` 资源组(Agent 访问密钥,供运行时内的 Agent 使用)不同。',
|
|
521
|
+
principals: ['user'],
|
|
522
|
+
commands: [
|
|
523
|
+
status,
|
|
524
|
+
chat,
|
|
525
|
+
fileLs,
|
|
526
|
+
fileTree,
|
|
527
|
+
fileDownload,
|
|
528
|
+
fileUpload,
|
|
529
|
+
fileMkdir,
|
|
530
|
+
fileRename,
|
|
531
|
+
fileRm,
|
|
532
|
+
automationList,
|
|
533
|
+
automationGet,
|
|
534
|
+
automationCreate,
|
|
535
|
+
automationUpdate,
|
|
536
|
+
toggle('automation enable', 'enable', '启用'),
|
|
537
|
+
toggle('automation disable', 'disable', '停用'),
|
|
538
|
+
automationDelete,
|
|
539
|
+
automationRun,
|
|
540
|
+
automationExecutions,
|
|
541
|
+
],
|
|
542
|
+
timers,
|
|
543
|
+
clampChatTimeout,
|
|
544
|
+
};
|
package/lib/commands/help.js
CHANGED
|
@@ -17,6 +17,7 @@ const ENVIRONMENT = `环境变量
|
|
|
17
17
|
WD_CLI_PROFILE 使用哪个 profile,等价于 --profile
|
|
18
18
|
WD_CLI_TIMEOUT_MS 请求超时毫秒数,等价于 --timeout-ms
|
|
19
19
|
WD_CLI_CHAT_BASE_URL 对话端点基址(与其余 Open API 不同域名时用)
|
|
20
|
+
WD_CLI_BRIDGE_URL daemon 外连的 bridge 地址;缺省按 <平台基址>/bridge/ 访问
|
|
20
21
|
WD_CLI_CONFIG_DIR 配置目录,覆盖默认的 XDG 位置
|
|
21
22
|
XDG_CONFIG_HOME 未设 WD_CLI_CONFIG_DIR 时,配置放在 $XDG_CONFIG_HOME/wd-cli
|
|
22
23
|
NO_COLOR 置任意非空值即关闭彩色输出
|
package/lib/commands/index.js
CHANGED
|
@@ -14,6 +14,7 @@ const TOPIC_MODULES = [
|
|
|
14
14
|
require('./config'),
|
|
15
15
|
require('./skill'),
|
|
16
16
|
require('./kb'),
|
|
17
|
+
require('./tool'),
|
|
17
18
|
require('./agent'),
|
|
18
19
|
require('./session'),
|
|
19
20
|
require('./credential'),
|
|
@@ -21,6 +22,10 @@ const TOPIC_MODULES = [
|
|
|
21
22
|
require('./dataset'),
|
|
22
23
|
require('./observability'),
|
|
23
24
|
require('./automation'),
|
|
25
|
+
require('./diwork'),
|
|
26
|
+
require('./daemon'),
|
|
27
|
+
require('./open'),
|
|
28
|
+
require('./device'),
|
|
24
29
|
require('./api'),
|
|
25
30
|
require('./completion'),
|
|
26
31
|
require('./help'),
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* `wd-cli open [dir]`(add-local-agent-projects):把一个本机目录作为项目接入 DiWork 本机运行时,
|
|
5
|
+
* 对标 `code .` / `codex .`。
|
|
6
|
+
*
|
|
7
|
+
* 1. 目录不在 daemon 白名单内:交互终端确认后把该目录加入白名单(非交互须 --yes);
|
|
8
|
+
* 2. 写入 daemon.json 的 projects(按路径去重),运行中的 daemon 监听到变化即重报清单,平台登记为项目;
|
|
9
|
+
* 3. 打印本机运行时页面链接。
|
|
10
|
+
*
|
|
11
|
+
* 网页不能扩大白名单——加根目录只发生在本机这一步(design D1/D6)。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const fs = require('node:fs');
|
|
15
|
+
const os = require('node:os');
|
|
16
|
+
const path = require('node:path');
|
|
17
|
+
|
|
18
|
+
const output = require('../output');
|
|
19
|
+
const { CliError, EXIT } = output;
|
|
20
|
+
const dataInput = require('../data');
|
|
21
|
+
const state = require('../daemon/state');
|
|
22
|
+
const roots = require('../daemon/roots');
|
|
23
|
+
|
|
24
|
+
function expandHome(dir) {
|
|
25
|
+
if (dir === '~') return os.homedir();
|
|
26
|
+
if (dir.startsWith('~/')) return path.join(os.homedir(), dir.slice(2));
|
|
27
|
+
return dir;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const run = {
|
|
31
|
+
name: '',
|
|
32
|
+
summary: '把本机目录作为项目接入 DiWork 本机运行时(缺省当前目录)',
|
|
33
|
+
workspaceOptional: true,
|
|
34
|
+
skipPrincipalCheck: true,
|
|
35
|
+
args: [{ name: 'dir', summary: '目录路径(缺省当前目录)' }],
|
|
36
|
+
examples: ['wd-cli open', 'wd-cli open ~/code/agent-infra', 'wd-cli open . --yes'],
|
|
37
|
+
async run(ctx) {
|
|
38
|
+
const env = ctx.env;
|
|
39
|
+
const target = path.resolve(expandHome(ctx.args[0] || '.'));
|
|
40
|
+
let real;
|
|
41
|
+
try {
|
|
42
|
+
real = fs.realpathSync.native(target);
|
|
43
|
+
} catch {
|
|
44
|
+
throw new CliError(`目录不存在:${target}`, EXIT.USAGE);
|
|
45
|
+
}
|
|
46
|
+
if (!fs.statSync(real).isDirectory()) throw new CliError(`不是目录:${target}`, EXIT.USAGE);
|
|
47
|
+
|
|
48
|
+
let daemonConfig = state.loadDaemonConfig(env);
|
|
49
|
+
let addedRoot = false;
|
|
50
|
+
if (!roots.resolveAllowedCwd(real, daemonConfig.allowedRoots)) {
|
|
51
|
+
output.info(`${real} 不在本机白名单内,Agent 只能在白名单目录里工作。`, ctx.flags);
|
|
52
|
+
const ok = await dataInput.confirm('把该目录加入白名单?', ctx.flags);
|
|
53
|
+
if (!ok) {
|
|
54
|
+
output.info('已取消', ctx.flags);
|
|
55
|
+
return EXIT.OK;
|
|
56
|
+
}
|
|
57
|
+
daemonConfig = { ...daemonConfig, allowedRoots: roots.addRoot(daemonConfig.allowedRoots, real).roots };
|
|
58
|
+
addedRoot = true;
|
|
59
|
+
}
|
|
60
|
+
const openedAt = new Date().toISOString();
|
|
61
|
+
daemonConfig = { ...daemonConfig, projects: state.addProject(daemonConfig.projects, real, openedAt) };
|
|
62
|
+
state.saveDaemonConfig(daemonConfig, env);
|
|
63
|
+
|
|
64
|
+
const deviceId = state.deviceId(env);
|
|
65
|
+
const base = ctx.runtime && ctx.runtime.baseUrl ? ctx.runtime.baseUrl : '';
|
|
66
|
+
const url = base ? `${base}/work/local?device=${encodeURIComponent(deviceId)}` : null;
|
|
67
|
+
const pid = state.readPid(env);
|
|
68
|
+
const running = Boolean(pid && state.isAlive(pid));
|
|
69
|
+
|
|
70
|
+
if (output.resolveFormat(ctx.flags) !== 'table' || ctx.flags.json || ctx.flags.jq) {
|
|
71
|
+
output.print({ path: real, addedRoot, deviceId, openedAt, url, daemonRunning: running }, { flags: ctx.flags });
|
|
72
|
+
return EXIT.OK;
|
|
73
|
+
}
|
|
74
|
+
if (addedRoot) output.success(`已加入白名单:${real}`, ctx.flags);
|
|
75
|
+
output.success(`已作为项目打开:${real}`, ctx.flags);
|
|
76
|
+
if (!running) {
|
|
77
|
+
output.warn('daemon 未在运行,项目会在 daemon 启动后同步到平台:wd-cli daemon start', ctx.flags);
|
|
78
|
+
}
|
|
79
|
+
if (url) output.info(`在浏览器中打开:${url}`, ctx.flags);
|
|
80
|
+
return EXIT.OK;
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
module.exports = {
|
|
85
|
+
id: 'open',
|
|
86
|
+
summary: '把本机目录作为项目接入 DiWork 本机运行时',
|
|
87
|
+
description: '目录不在 daemon 白名单内时会先确认加入;运行中的 daemon 会立即把项目同步到平台。',
|
|
88
|
+
commands: [run],
|
|
89
|
+
};
|