@dmall-inc/wd-cli 0.2.0 → 0.4.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 +88 -0
- package/docs/design-references.md +2 -0
- package/lib/args.js +2 -1
- package/lib/auth.js +1 -1
- package/lib/commands/daemon.js +411 -0
- package/lib/commands/device.js +92 -0
- package/lib/commands/diwork.js +544 -0
- package/lib/commands/index.js +5 -0
- package/lib/commands/open.js +89 -0
- package/lib/commands/tool.js +327 -0
- package/lib/daemon/agui.js +63 -0
- package/lib/daemon/channel.js +183 -0
- package/lib/daemon/enroll.js +78 -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
package/README.md
CHANGED
|
@@ -216,6 +216,32 @@ wd-cli kb share create|list 12 99
|
|
|
216
216
|
|
|
217
217
|
批量上传时单个文件失败不会中断其余文件,最后按整体结果给退出码。
|
|
218
218
|
|
|
219
|
+
### tool 工具
|
|
220
|
+
|
|
221
|
+
```bash
|
|
222
|
+
wd-cli tool list [--scope personal|team|company] [--source mcp] [--keyword 工单] [--paginate]
|
|
223
|
+
wd-cli tool get 12 # 认证与自定义参数值一律脱敏
|
|
224
|
+
wd-cli tool subtools 12 # 子工具与授权状态
|
|
225
|
+
wd-cli tool subtools 12 --name search_docs -o json # 单个子工具的 inputSchema
|
|
226
|
+
|
|
227
|
+
wd-cli tool create --file mcp-tool.json # - 为标准输入
|
|
228
|
+
wd-cli tool update 12 --file patch.json
|
|
229
|
+
wd-cli tool delete 12 --yes
|
|
230
|
+
wd-cli tool test 12 # 按已保存配置探测连通性
|
|
231
|
+
|
|
232
|
+
wd-cli tool invoke 12 search_docs --arg query=报销 --arg limit=5
|
|
233
|
+
wd-cli tool invoke 30 getOrder --args '{"orderId":"A1"}'
|
|
234
|
+
echo '{"orderId":"A1"}' | wd-cli tool invoke 30 getOrder --args-file -
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
`invoke` 直接调用工具(不经过 Agent),**会产生真实副作用**;连接地址与认证用平台上已保存的配置,CLI 只传子工具名与入参。
|
|
238
|
+
|
|
239
|
+
- 入参合并顺序 `--args-file` < `--args` < `--arg`(后者覆盖同名键);`--arg` 的值先按 JSON 解析(`5`、`true`、`[1,2]`、`{"a":1}`),失败当字符串;要保留前导零等字面量写成 JSON 字符串:`--arg 'id="007"'`;键支持点号嵌套:`--arg filter.status=open`。
|
|
240
|
+
- `--timeout-ms` 同时作为服务端调用超时(上限 120 秒);缺省等服务端按工具配置执行。
|
|
241
|
+
- 退出码:成功 0;工具自身报错(MCP `isError` / REST HTTP ≥ 300)或调用失败 1;子工具未获授权(业务码 403)3。
|
|
242
|
+
- 工具认证引用个人凭证时按当前登录用户解引用;工作空间令牌(`wat_`)只能查看与调用本空间团队工具和免审批的公司级工具,不能解引用个人凭证;`create` / `update` / `delete` 需登录态。
|
|
243
|
+
- 创建工具时认证值建议写凭证引用(`auth.valueSource=credential` + `auth.credentialKey`),不要把明文放进 JSON 文件。
|
|
244
|
+
|
|
219
245
|
### agent 应用与对话
|
|
220
246
|
|
|
221
247
|
```bash
|
|
@@ -321,6 +347,68 @@ wd-cli automation create --session-id s-1 --data @task.json
|
|
|
321
347
|
wd-cli download-link create --data '{"path":"/data/report.xlsx"}'
|
|
322
348
|
```
|
|
323
349
|
|
|
350
|
+
### diwork 我的 DiWork
|
|
351
|
+
|
|
352
|
+
以登录用户本人身份使用自己的 DiWork(AI 数字员工):运行环境、调用、工作区文件、自动化任务。**仅接受登录态**(`wd-cli auth login`),令牌直连会被本地拒绝。与 `agent chat` 一样走对话基址:单入口部署零配置,对话端点拆在别的域名时先 `wd-cli config set chatBaseUrl <server 地址>`。
|
|
353
|
+
|
|
354
|
+
```bash
|
|
355
|
+
# 运行环境
|
|
356
|
+
wd-cli diwork status # 只读探测
|
|
357
|
+
wd-cli diwork status --ensure # 未就绪时触发供给;--retry 供给失败后重来
|
|
358
|
+
|
|
359
|
+
# 调用:在你的 DiWork 内跑一轮,回复直出;会话与 Web 端同源(Web 会话列表可见)
|
|
360
|
+
wd-cli diwork chat -m "把昨天的销售数据整理成表格放到 reports/"
|
|
361
|
+
wd-cli diwork chat -m "再按区域汇总" --session-id <上一轮提示的 id>
|
|
362
|
+
cat task.md | wd-cli diwork chat -m - --timeout-ms 600000 -o json
|
|
363
|
+
# 运行环境供给中时自动等待(缺省 180s,--wait-ms 调整);执行超时缺省 300s、上限 600s
|
|
364
|
+
|
|
365
|
+
# 工作区文件(与 Web 文件管理同一份)
|
|
366
|
+
wd-cli diwork file ls reports
|
|
367
|
+
wd-cli diwork file tree -o json
|
|
368
|
+
wd-cli diwork file upload ./a.csv ./b.csv --path inbox
|
|
369
|
+
wd-cli diwork file download reports/日报.xlsx -O ./out/
|
|
370
|
+
wd-cli diwork file mkdir reports/2026
|
|
371
|
+
wd-cli diwork file rename reports/draft.md final.md
|
|
372
|
+
wd-cli diwork file rm tmp/a.log tmp/b.log --yes # 逐项结果,任一失败退出码 1
|
|
373
|
+
|
|
374
|
+
# 自动化任务(与 Web 自动化页同一套;归属恒为本人)
|
|
375
|
+
wd-cli diwork automation list
|
|
376
|
+
wd-cli diwork automation create --file daily.json # name / scheduleType / cronExpression|runAt / params / pushTargets
|
|
377
|
+
wd-cli diwork automation run 12 --params "只看华东区" # 立即执行一次,结果非 SUCCESS 退出码 1
|
|
378
|
+
wd-cli diwork automation executions 12 --status FAILED
|
|
379
|
+
wd-cli diwork automation disable 12
|
|
380
|
+
wd-cli diwork automation delete 12 --yes
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
> `automation` 资源组(上一节)是 Agent 访问密钥 + `--session-id`,供 DiWork 运行时内的 Agent 代用户建任务;人在终端里管理自己的任务用 `diwork automation`。
|
|
384
|
+
|
|
385
|
+
### daemon / device 运行时(本机 Agent 接入 DiWork)
|
|
386
|
+
|
|
387
|
+
把本机的 Claude Code、Codex、Pi 接入 DiWork「运行时」,在任意设备的浏览器里给它们发任务、看过程、审批工具调用。
|
|
388
|
+
daemon 主动外连平台,本机不开端口;只在白名单目录里工作;设备只有你自己能看到和使用。
|
|
389
|
+
|
|
390
|
+
```bash
|
|
391
|
+
wd-cli auth login # 统一身份登录(daemon 只认登录态,不接受 --token)
|
|
392
|
+
wd-cli daemon start # 后台启动,首次启动自动登记本机;--foreground 前台运行
|
|
393
|
+
cd ~/code/my-repo && wd-cli open # 把当前目录作为项目接入(不在白名单时先确认加入),打印页面链接
|
|
394
|
+
wd-cli daemon roots add ~/code # 也可直接维护白名单根目录(list / remove);根目录内的子目录可在页面里选为项目
|
|
395
|
+
wd-cli daemon status # 运行状态、连接、允许目录、运行时
|
|
396
|
+
wd-cli daemon runtimes # 探测本机运行时(claude / codex / pi)
|
|
397
|
+
wd-cli daemon logs -f # 跟随日志(~/.config/wd-cli/daemon.log)
|
|
398
|
+
wd-cli daemon service install # 开机自启(macOS launchd / Linux systemd);print 只打印配置
|
|
399
|
+
wd-cli daemon stop
|
|
400
|
+
wd-cli device list # 我登记的设备(* 为本机);rename <id> <名称> / revoke <id>
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
- 运行时探测:PATH 上能正常回答 `--version` 的 `claude` / `codex` / `pi`。Claude Code、Codex 经 ACP 适配器驱动(优先 PATH 上的 `claude-agent-acp` / `codex-acp`,否则 `npx -y` 按平台清单版本拉取);Pi 经 `pi --mode rpc` 驱动并注入审批扩展。
|
|
404
|
+
- 自动恢复:运行中每 60 秒复检一次运行时(`--version` 结果按二进制缓存,二进制没变不重复起进程);页面选了不可用的运行时会当场复检,运行时启动失败或进程退出也会触发复检,可用性变化即重报给平台,开机时没探测到、后来才安装或登录的运行时不用重启 daemon。适配器 120 秒内未完成初始化(如卡在等待登录)即结束本轮;取消后 10 秒仍不收口的适配器会被强制重启,下一轮按原会话续接。
|
|
405
|
+
- 审批:只读类工具直接放行,其余回到页面审批,超时(平台配置,默认 10 分钟)自动拒绝;`~/.config/wd-cli/daemon.json` 的 `autoApprove` 可列出额外放行的工具名。
|
|
406
|
+
- 覆盖命令 / 停用某个运行时:在 `daemon.json` 写 `"runtimes": {"claude": {"command": ["my-acp-adapter"]}, "codex": {"enabled": false}}`,运行中的 daemon 3 秒内生效。
|
|
407
|
+
- bridge 地址:`--bridge-url` > `WD_CLI_BRIDGE_URL` > `daemon.json` 的 `bridgeUrl` > 平台下发配置 > 平台基址。
|
|
408
|
+
- 设备令牌(`ldt_`)存系统钥匙串账号 `device:<profile>`;被撤销后 daemon 会用登录身份重新登记一次,仍失败即退出。
|
|
409
|
+
- 扩展:`wd-cli daemon executor add <npm 包>` 安装声明了 `wdCliExecutor` 的执行器包。
|
|
410
|
+
- 项目:页面侧栏按项目(工作目录)分组会话。页面「添加项目」只能浏览白名单根目录以内的子目录;白名单外的目录只能在本机用 `wd-cli open` 加入(非交互环境须 `--yes`)。打开记录写在 `daemon.json` 的 `projects`,daemon 重报清单后平台登记为项目。
|
|
411
|
+
|
|
324
412
|
### completion 补全
|
|
325
413
|
|
|
326
414
|
```bash
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
|--------|---------------|-----------|
|
|
11
11
|
| `auth login / status / logout` 命令族与文案(`✓ Logged in as X`、状态按 host 分组列出) | `pkg/cmd/auth/**` | `lib/commands/auth.js` |
|
|
12
12
|
| 通用逃生口:`-X` 方法、`-f` 字符串字段、`-F` 带类型推断字段、`--input` 请求体、`-H` 头、`--paginate` | `pkg/cmd/api/api.go` | `lib/commands/api.js` |
|
|
13
|
+
| `-F` 字段类型推断 + `--input` 请求体,二者可叠加、字段覆盖请求体同名键 | `pkg/cmd/api/api.go` | `tool invoke`:`--args-file` < `--args` < `--arg`;`--arg` 值按 JSON 解析(比 `-F` 宽:可直接写数组 / 对象),失败当字符串 |
|
|
13
14
|
| `--json <fields>` 选字段 + `--jq <expr>` 过滤,非 TTY 自动机器可读 | `pkg/cmdutil/json_flags.go` | `lib/output.js`、`lib/jq.js` |
|
|
14
15
|
| 令牌优先存 OS 密钥链,不可用时回落配置文件 | `internal/keyring` | `lib/keyring.js`(P2),回落 `hosts.json` |
|
|
15
16
|
| 环境变量令牌覆盖登录态(`GH_TOKEN`) | `internal/config` | `WD_CLI_TOKEN`,语义完全一致 |
|
|
@@ -35,6 +36,7 @@
|
|
|
35
36
|
| `config use-context` / `current-context` 的「当前上下文」模型 | `workspace use` / `workspace current` |
|
|
36
37
|
| `--namespace` 单次覆盖当前上下文而不改配置 | `--workspace` 单次覆盖 |
|
|
37
38
|
| `-o json\|yaml\|wide\|name` | `--output table\|json\|raw`(`-o`) |
|
|
39
|
+
| `kubectl set` / `helm --set a.b=v` 的点号嵌套赋值 | `tool invoke --arg filter.status=open`(点号键展开为嵌套对象) |
|
|
38
40
|
|
|
39
41
|
## 4. AWS CLI
|
|
40
42
|
|
package/lib/args.js
CHANGED
|
@@ -193,8 +193,9 @@ function renderRootHelp(registry) {
|
|
|
193
193
|
lines.push('');
|
|
194
194
|
const groups = [
|
|
195
195
|
['接入', ['auth', 'workspace', 'config']],
|
|
196
|
-
['资源', ['skill', 'kb', 'agent', 'session']],
|
|
196
|
+
['资源', ['skill', 'kb', 'tool', 'agent', 'session']],
|
|
197
197
|
['运营', ['credential', 'eval', 'dataset', 'trace', 'obs', 'score', 'automation', 'download-link']],
|
|
198
|
+
['本机', ['open', 'daemon', 'device']],
|
|
198
199
|
['其它', ['api', 'completion', 'help']],
|
|
199
200
|
];
|
|
200
201
|
for (const [label, ids] of groups) {
|
package/lib/auth.js
CHANGED
|
@@ -59,7 +59,7 @@ function assertPrincipalAllowed(runtime, principal, topic, command, flags = {})
|
|
|
59
59
|
|
|
60
60
|
const wanted = allowed.map((p) => LABEL[p]).join(' 或 ');
|
|
61
61
|
const hints = allowed.map((p) => HOW_TO_GET[p]).filter(Boolean);
|
|
62
|
-
hints.push(HOW_TO_GET.user);
|
|
62
|
+
if (!allowed.includes('user')) hints.push(HOW_TO_GET.user);
|
|
63
63
|
throw new CliError(
|
|
64
64
|
`当前用的是${LABEL[principal]},此命令需要${wanted}`,
|
|
65
65
|
EXIT.USAGE,
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 本机守护进程(add-local-agent-runtime):把本机的 Claude Code / Codex / Pi 接入 DiWork「运行时」。
|
|
5
|
+
*
|
|
6
|
+
* daemon 主动外连平台 bridge,本机不开端口;只在 roots 白名单目录里执行;危险工具调用回到页面审批。
|
|
7
|
+
* 生命周期命令对标 `docker`/`tailscale` 的 daemon 管理习惯:start(缺省后台)/ stop / status / logs。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const fs = require('node:fs');
|
|
11
|
+
const path = require('node:path');
|
|
12
|
+
const { spawn, execFileSync } = require('node:child_process');
|
|
13
|
+
|
|
14
|
+
const output = require('../output');
|
|
15
|
+
const { CliError, EXIT } = output;
|
|
16
|
+
const state = require('../daemon/state');
|
|
17
|
+
const roots = require('../daemon/roots');
|
|
18
|
+
const enrollLib = require('../daemon/enroll');
|
|
19
|
+
const runtimesLib = require('../daemon/runtimes');
|
|
20
|
+
const service = require('../daemon/service');
|
|
21
|
+
|
|
22
|
+
const BRIDGE_FLAG = { 'bridge-url': { type: 'string', summary: 'bridge 地址(缺省取平台下发配置或平台基址)' } };
|
|
23
|
+
|
|
24
|
+
function requireUser(ctx) {
|
|
25
|
+
if (ctx.principal !== 'user') {
|
|
26
|
+
throw new CliError('daemon 需要统一身份登录态', EXIT.USAGE, { hint: '先执行 wd-cli auth login(daemon 不接受 --token / WD_CLI_TOKEN)' });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function timestamped(message) {
|
|
31
|
+
return `${new Date().toISOString()} ${message}\n`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function runningPid(env) {
|
|
35
|
+
const pid = state.readPid(env);
|
|
36
|
+
return pid && state.isAlive(pid) ? pid : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 连接已有结论(已连上 / 已断开),不再是启动中的过渡态。 */
|
|
40
|
+
const SETTLED_CONNECTIONS = new Set(['connected', 'disconnected']);
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 后台启动后等 daemon 写出属于自己的状态快照,并尽量等到连接有结论(最多 timeoutMs),
|
|
44
|
+
* 免得紧接着展示的状态还是上一次运行留下的快照或「连接中」。
|
|
45
|
+
*/
|
|
46
|
+
async function waitForSnapshot(env, pid, timeoutMs = 8000) {
|
|
47
|
+
const deadline = Date.now() + timeoutMs;
|
|
48
|
+
while (Date.now() < deadline) {
|
|
49
|
+
if (!state.isAlive(pid)) return;
|
|
50
|
+
const snap = state.readStatus(env);
|
|
51
|
+
if (snap && snap.pid === pid && SETTLED_CONNECTIONS.has(snap.connection)) return;
|
|
52
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const start = {
|
|
57
|
+
name: 'start',
|
|
58
|
+
summary: '启动 daemon(缺省后台运行,--foreground 前台运行)',
|
|
59
|
+
workspaceOptional: true,
|
|
60
|
+
principals: ['user'],
|
|
61
|
+
flags: {
|
|
62
|
+
foreground: { type: 'boolean', summary: '在当前终端前台运行(服务管理器用)' },
|
|
63
|
+
...BRIDGE_FLAG,
|
|
64
|
+
},
|
|
65
|
+
examples: ['wd-cli daemon start', 'wd-cli daemon start --foreground'],
|
|
66
|
+
async run(ctx) {
|
|
67
|
+
requireUser(ctx);
|
|
68
|
+
const env = ctx.env;
|
|
69
|
+
const paths = state.paths(env);
|
|
70
|
+
const existing = runningPid(env);
|
|
71
|
+
if (existing && existing !== process.pid) {
|
|
72
|
+
output.info(`daemon 已在运行(PID ${existing})`, ctx.flags);
|
|
73
|
+
return status.run(ctx);
|
|
74
|
+
}
|
|
75
|
+
// 先在前台完成登记,让「未登录 / 功能未开启 / 设备冲突」这类错误直接报在终端
|
|
76
|
+
await enrollLib.ensureDeviceToken(ctx);
|
|
77
|
+
const daemonConfig = state.loadDaemonConfig(env);
|
|
78
|
+
if (!daemonConfig.allowedRoots.length) {
|
|
79
|
+
output.warn('还没有允许的工作目录,页面上将无法发起会话;用 wd-cli daemon roots add <目录> 添加', ctx.flags);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (ctx.flags.foreground) {
|
|
83
|
+
state.writePid(process.pid, env);
|
|
84
|
+
const log = (m) => process.stderr.write(timestamped(m));
|
|
85
|
+
const { runDaemon } = require('../daemon');
|
|
86
|
+
try {
|
|
87
|
+
await runDaemon(ctx, { log });
|
|
88
|
+
} finally {
|
|
89
|
+
if (state.readPid(env) === process.pid) state.clearPid(env);
|
|
90
|
+
}
|
|
91
|
+
return EXIT.OK;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
fs.mkdirSync(paths.dir, { recursive: true, mode: 0o700 });
|
|
95
|
+
const logFd = fs.openSync(paths.log, 'a', 0o600);
|
|
96
|
+
const args = [path.resolve(__dirname, '..', '..', 'bin', 'wd-cli.js'), 'daemon', 'start', '--foreground', '--profile', ctx.runtime.profileName];
|
|
97
|
+
if (ctx.flags.baseUrl) args.push('--base-url', ctx.flags.baseUrl);
|
|
98
|
+
if (ctx.flags.bridgeUrl) args.push('--bridge-url', ctx.flags.bridgeUrl);
|
|
99
|
+
const child = spawn(process.execPath, args, { detached: true, stdio: ['ignore', logFd, logFd], env });
|
|
100
|
+
child.unref();
|
|
101
|
+
fs.closeSync(logFd);
|
|
102
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
103
|
+
if (!state.isAlive(child.pid)) {
|
|
104
|
+
throw new CliError('daemon 启动后立即退出', EXIT.BUSINESS, { hint: `查看日志:wd-cli daemon logs(${paths.log})` });
|
|
105
|
+
}
|
|
106
|
+
output.success(`daemon 已在后台启动(PID ${child.pid}),日志:${paths.log}`, ctx.flags);
|
|
107
|
+
// 启动后直接展示状态(同 wd-cli daemon status),连接有结论前最多等几秒
|
|
108
|
+
await waitForSnapshot(env, child.pid);
|
|
109
|
+
output.info('', ctx.flags);
|
|
110
|
+
const code = await status.run(ctx);
|
|
111
|
+
output.info('\n开机自启用 wd-cli daemon service install', ctx.flags);
|
|
112
|
+
return code;
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const stop = {
|
|
117
|
+
name: 'stop',
|
|
118
|
+
summary: '停止后台 daemon',
|
|
119
|
+
workspaceOptional: true,
|
|
120
|
+
skipPrincipalCheck: true,
|
|
121
|
+
async run(ctx) {
|
|
122
|
+
const pid = runningPid(ctx.env);
|
|
123
|
+
if (!pid) {
|
|
124
|
+
state.clearPid(ctx.env);
|
|
125
|
+
output.info('daemon 未在运行', ctx.flags);
|
|
126
|
+
return EXIT.OK;
|
|
127
|
+
}
|
|
128
|
+
process.kill(pid, 'SIGTERM');
|
|
129
|
+
const deadline = Date.now() + 8000;
|
|
130
|
+
while (state.isAlive(pid) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 200));
|
|
131
|
+
if (state.isAlive(pid)) process.kill(pid, 'SIGKILL');
|
|
132
|
+
state.clearPid(ctx.env);
|
|
133
|
+
output.success(`daemon 已停止(PID ${pid})`, ctx.flags);
|
|
134
|
+
if (service.targetPath() && fs.existsSync(service.targetPath())) {
|
|
135
|
+
output.info('已安装开机自启服务,服务管理器可能会重新拉起;彻底停用请执行 wd-cli daemon service uninstall', ctx.flags);
|
|
136
|
+
}
|
|
137
|
+
return EXIT.OK;
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const status = {
|
|
142
|
+
name: 'status',
|
|
143
|
+
summary: '查看 daemon 运行状态、连接与运行时',
|
|
144
|
+
workspaceOptional: true,
|
|
145
|
+
skipPrincipalCheck: true,
|
|
146
|
+
async run(ctx) {
|
|
147
|
+
const env = ctx.env;
|
|
148
|
+
const pid = runningPid(env);
|
|
149
|
+
const snap = state.readStatus(env) || {};
|
|
150
|
+
const daemonConfig = state.loadDaemonConfig(env);
|
|
151
|
+
const result = {
|
|
152
|
+
running: Boolean(pid),
|
|
153
|
+
pid: pid || null,
|
|
154
|
+
deviceId: state.deviceId(env),
|
|
155
|
+
connection: pid ? snap.connection || 'unknown' : 'stopped',
|
|
156
|
+
bridgeUrl: snap.bridgeUrl || null,
|
|
157
|
+
activeRuns: pid ? snap.activeRuns || 0 : 0,
|
|
158
|
+
roots: daemonConfig.allowedRoots,
|
|
159
|
+
runtimes: snap.runtimes || null,
|
|
160
|
+
updatedAt: snap.updatedAt || null,
|
|
161
|
+
};
|
|
162
|
+
if (output.resolveFormat(ctx.flags) !== 'table' || ctx.flags.json || ctx.flags.jq) {
|
|
163
|
+
output.print(result, { flags: ctx.flags });
|
|
164
|
+
return EXIT.OK;
|
|
165
|
+
}
|
|
166
|
+
const lines = [
|
|
167
|
+
`状态 ${result.running ? output.style.green('运行中', ctx.flags) : output.style.dim('未运行', ctx.flags)}${pid ? `(PID ${pid})` : ''}`,
|
|
168
|
+
`设备 ID ${result.deviceId}`,
|
|
169
|
+
`连接 ${result.connection}${result.bridgeUrl ? ` ${result.bridgeUrl}` : ''}`,
|
|
170
|
+
`进行中 ${result.activeRuns} 轮`,
|
|
171
|
+
`允许目录 ${result.roots.length ? result.roots.join('\n ') : output.style.yellow('(无,用 wd-cli daemon roots add <目录> 添加)', ctx.flags)}`,
|
|
172
|
+
];
|
|
173
|
+
if (Array.isArray(result.runtimes)) {
|
|
174
|
+
lines.push(`运行时 ${result.runtimes.map((r) => `${r.id}${r.available ? '' : '(不可用)'}`).join(' ')}`);
|
|
175
|
+
}
|
|
176
|
+
process.stdout.write(`${lines.join('\n')}\n`);
|
|
177
|
+
return EXIT.OK;
|
|
178
|
+
},
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const logs = {
|
|
182
|
+
name: 'logs',
|
|
183
|
+
summary: '查看 daemon 日志(-f 持续跟随)',
|
|
184
|
+
workspaceOptional: true,
|
|
185
|
+
skipPrincipalCheck: true,
|
|
186
|
+
flags: {
|
|
187
|
+
follow: { type: 'boolean', short: 'f', summary: '持续输出新日志' },
|
|
188
|
+
lines: { type: 'number', short: 'n', summary: '显示最后多少行(默认 100)' },
|
|
189
|
+
},
|
|
190
|
+
async run(ctx) {
|
|
191
|
+
const file = state.paths(ctx.env).log;
|
|
192
|
+
if (!fs.existsSync(file)) {
|
|
193
|
+
output.info(`还没有日志:${file}`, ctx.flags);
|
|
194
|
+
return EXIT.OK;
|
|
195
|
+
}
|
|
196
|
+
const n = ctx.flags.lines || 100;
|
|
197
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
198
|
+
const tail = text.split('\n').slice(-(n + 1)).join('\n');
|
|
199
|
+
process.stdout.write(tail.endsWith('\n') ? tail : `${tail}\n`);
|
|
200
|
+
if (!ctx.flags.follow) return EXIT.OK;
|
|
201
|
+
let offset = fs.statSync(file).size;
|
|
202
|
+
await new Promise(() => {
|
|
203
|
+
fs.watchFile(file, { interval: 500 }, (cur) => {
|
|
204
|
+
if (cur.size < offset) offset = 0;
|
|
205
|
+
if (cur.size > offset) {
|
|
206
|
+
const fd = fs.openSync(file, 'r');
|
|
207
|
+
const buf = Buffer.alloc(cur.size - offset);
|
|
208
|
+
fs.readSync(fd, buf, 0, buf.length, offset);
|
|
209
|
+
fs.closeSync(fd);
|
|
210
|
+
offset = cur.size;
|
|
211
|
+
process.stdout.write(buf);
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
});
|
|
215
|
+
return EXIT.OK;
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
const RUNTIME_COLUMNS = [
|
|
220
|
+
{ key: 'id', label: 'ID' },
|
|
221
|
+
{ key: 'name', label: '名称' },
|
|
222
|
+
{ key: 'version', label: '版本' },
|
|
223
|
+
{ key: 'available', label: '可用' },
|
|
224
|
+
{ key: 'reason', label: '说明' },
|
|
225
|
+
];
|
|
226
|
+
|
|
227
|
+
const runtimesCmd = {
|
|
228
|
+
name: 'runtimes',
|
|
229
|
+
summary: '探测本机可用的运行时(Claude Code / Codex / Pi / 执行器包)',
|
|
230
|
+
workspaceOptional: true,
|
|
231
|
+
skipPrincipalCheck: true,
|
|
232
|
+
async run(ctx) {
|
|
233
|
+
const paths = state.paths(ctx.env);
|
|
234
|
+
const list = runtimesLib.detectAll({
|
|
235
|
+
daemonConfig: state.loadDaemonConfig(ctx.env),
|
|
236
|
+
manifest: {},
|
|
237
|
+
executorsDir: paths.executors,
|
|
238
|
+
log: (m) => ctx.log(m),
|
|
239
|
+
});
|
|
240
|
+
const rows = runtimesLib.toInventory(list).map((r) => ({ ...r, available: r.available ? '是' : '否', reason: r.reason || '' }));
|
|
241
|
+
output.print(output.resolveFormat(ctx.flags) === 'table' ? rows : runtimesLib.toInventory(list), {
|
|
242
|
+
flags: ctx.flags,
|
|
243
|
+
columns: RUNTIME_COLUMNS,
|
|
244
|
+
});
|
|
245
|
+
return EXIT.OK;
|
|
246
|
+
},
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
const rootsCmd = {
|
|
250
|
+
name: 'roots',
|
|
251
|
+
summary: '管理允许 Agent 工作的目录白名单:list | add <目录> | remove <目录>',
|
|
252
|
+
workspaceOptional: true,
|
|
253
|
+
skipPrincipalCheck: true,
|
|
254
|
+
args: [
|
|
255
|
+
{ name: 'action', summary: 'list(缺省)| add | remove' },
|
|
256
|
+
{ name: 'dir', summary: '目录路径' },
|
|
257
|
+
],
|
|
258
|
+
examples: ['wd-cli daemon roots add ~/code/my-repo', 'wd-cli daemon roots list', 'wd-cli daemon roots remove ~/code/old'],
|
|
259
|
+
async run(ctx) {
|
|
260
|
+
const action = ctx.args[0] || 'list';
|
|
261
|
+
const dir = ctx.args[1];
|
|
262
|
+
const daemonConfig = state.loadDaemonConfig(ctx.env);
|
|
263
|
+
if (action === 'list') {
|
|
264
|
+
const rows = daemonConfig.allowedRoots.map((r) => ({ path: r }));
|
|
265
|
+
output.print(output.resolveFormat(ctx.flags) === 'table' ? rows : daemonConfig.allowedRoots, {
|
|
266
|
+
flags: ctx.flags,
|
|
267
|
+
columns: [{ key: 'path', label: '目录' }],
|
|
268
|
+
empty: '还没有允许的目录,用 wd-cli daemon roots add <目录> 添加',
|
|
269
|
+
});
|
|
270
|
+
return EXIT.OK;
|
|
271
|
+
}
|
|
272
|
+
if (!dir) throw new CliError(`缺少目录参数:wd-cli daemon roots ${action} <目录>`, EXIT.USAGE);
|
|
273
|
+
const expanded = dir.startsWith('~') ? path.join(require('node:os').homedir(), dir.slice(1)) : dir;
|
|
274
|
+
if (action === 'add') {
|
|
275
|
+
let next;
|
|
276
|
+
try {
|
|
277
|
+
next = roots.addRoot(daemonConfig.allowedRoots, expanded);
|
|
278
|
+
} catch (error) {
|
|
279
|
+
throw new CliError(error.message, EXIT.USAGE);
|
|
280
|
+
}
|
|
281
|
+
state.saveDaemonConfig({ ...daemonConfig, allowedRoots: next.roots }, ctx.env);
|
|
282
|
+
output.success(`已允许:${next.added}`, ctx.flags);
|
|
283
|
+
return EXIT.OK;
|
|
284
|
+
}
|
|
285
|
+
if (action === 'remove') {
|
|
286
|
+
const next = roots.removeRoot(daemonConfig.allowedRoots, expanded);
|
|
287
|
+
if (next.length === daemonConfig.allowedRoots.length) {
|
|
288
|
+
throw new CliError(`白名单中没有:${dir}`, EXIT.USAGE, { hint: '用 wd-cli daemon roots list 查看' });
|
|
289
|
+
}
|
|
290
|
+
state.saveDaemonConfig({ ...daemonConfig, allowedRoots: next }, ctx.env);
|
|
291
|
+
output.success(`已移除:${dir}`, ctx.flags);
|
|
292
|
+
return EXIT.OK;
|
|
293
|
+
}
|
|
294
|
+
throw new CliError(`未知动作:${action}`, EXIT.USAGE, { hint: '可用:list | add | remove' });
|
|
295
|
+
},
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
const executorCmd = {
|
|
299
|
+
name: 'executor',
|
|
300
|
+
summary: '管理执行器包:list | add <包> | remove <包>(装在 ~/.config/wd-cli/executors)',
|
|
301
|
+
workspaceOptional: true,
|
|
302
|
+
principals: ['user'],
|
|
303
|
+
args: [
|
|
304
|
+
{ name: 'action', summary: 'list(缺省)| add | remove' },
|
|
305
|
+
{ name: 'package', summary: 'npm 包名,可带 @版本' },
|
|
306
|
+
],
|
|
307
|
+
examples: ['wd-cli daemon executor list', 'wd-cli daemon executor add @dmall-inc/wd-cli-executor-foo'],
|
|
308
|
+
async run(ctx) {
|
|
309
|
+
const action = ctx.args[0] || 'list';
|
|
310
|
+
const pkg = ctx.args[1];
|
|
311
|
+
const dir = state.paths(ctx.env).executors;
|
|
312
|
+
if (action === 'list') {
|
|
313
|
+
const packs = runtimesLib.detectPacks({ executorsDir: dir, log: (m) => ctx.log(m) });
|
|
314
|
+
output.print(packs.map((p) => ({ id: p.id, package: p.packageName, version: p.packageVersion, available: p.available ? '是' : '否' })), {
|
|
315
|
+
flags: ctx.flags,
|
|
316
|
+
columns: [{ key: 'id', label: 'ID' }, { key: 'package', label: '包' }, { key: 'version', label: '版本' }, { key: 'available', label: '可用' }],
|
|
317
|
+
empty: '没有安装执行器包(Claude Code / Codex / Pi 为内置执行器,无需安装)',
|
|
318
|
+
});
|
|
319
|
+
return EXIT.OK;
|
|
320
|
+
}
|
|
321
|
+
if (!pkg) throw new CliError(`缺少包名:wd-cli daemon executor ${action} <包>`, EXIT.USAGE);
|
|
322
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
323
|
+
if (!fs.existsSync(path.join(dir, 'package.json'))) {
|
|
324
|
+
fs.writeFileSync(path.join(dir, 'package.json'), `${JSON.stringify({ name: 'wd-cli-executors', private: true }, null, 2)}\n`);
|
|
325
|
+
}
|
|
326
|
+
let spec = pkg;
|
|
327
|
+
if (action === 'add' && !/@[^/]+$/.test(pkg.replace(/^@/, ''))) {
|
|
328
|
+
const manifestResp = await enrollLib.fetchManifest(ctx);
|
|
329
|
+
const entry = manifestResp && manifestResp.manifest && manifestResp.manifest.executors
|
|
330
|
+
&& Object.values(manifestResp.manifest.executors).find((e) => e && e.package === pkg);
|
|
331
|
+
if (entry && entry.version && entry.version !== 'latest') spec = `${pkg}@${entry.version}`;
|
|
332
|
+
}
|
|
333
|
+
const npmArgs = action === 'add' ? ['install', '--prefix', dir, '--no-audit', '--no-fund', spec]
|
|
334
|
+
: action === 'remove' ? ['uninstall', '--prefix', dir, pkg] : null;
|
|
335
|
+
if (!npmArgs) throw new CliError(`未知动作:${action}`, EXIT.USAGE, { hint: '可用:list | add | remove' });
|
|
336
|
+
try {
|
|
337
|
+
execFileSync(process.platform === 'win32' ? 'npm.cmd' : 'npm', npmArgs, { stdio: 'inherit' });
|
|
338
|
+
} catch (error) {
|
|
339
|
+
throw new CliError(`npm ${npmArgs[0]} 失败:${error.message}`, EXIT.BUSINESS);
|
|
340
|
+
}
|
|
341
|
+
output.success(`${action === 'add' ? '已安装' : '已移除'}:${spec}(运行中的 daemon 会在 daemon.json 变更或重启后重新探测)`, ctx.flags);
|
|
342
|
+
return EXIT.OK;
|
|
343
|
+
},
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
const serviceCmd = {
|
|
347
|
+
name: 'service',
|
|
348
|
+
summary: '开机自启:install | uninstall | print(macOS launchd / Linux systemd)',
|
|
349
|
+
workspaceOptional: true,
|
|
350
|
+
skipPrincipalCheck: true,
|
|
351
|
+
args: [{ name: 'action', required: true, summary: 'install | uninstall | print' }],
|
|
352
|
+
examples: ['wd-cli daemon service install', 'wd-cli daemon service print'],
|
|
353
|
+
async run(ctx) {
|
|
354
|
+
const action = ctx.args[0];
|
|
355
|
+
const opts = { profileName: ctx.runtime.profileName, logPath: state.paths(ctx.env).log, env: ctx.env };
|
|
356
|
+
if (action === 'print') {
|
|
357
|
+
const r = service.install({ ...opts, dryRun: true });
|
|
358
|
+
process.stdout.write(`# ${r.file}\n${r.content}`);
|
|
359
|
+
return EXIT.OK;
|
|
360
|
+
}
|
|
361
|
+
if (action === 'install') {
|
|
362
|
+
if (ctx.principal !== 'user') requireUser(ctx);
|
|
363
|
+
await enrollLib.ensureDeviceToken(ctx);
|
|
364
|
+
const pid = runningPid(ctx.env);
|
|
365
|
+
if (pid) {
|
|
366
|
+
output.info(`先停止当前后台 daemon(PID ${pid}),交给服务管理器托管`, ctx.flags);
|
|
367
|
+
process.kill(pid, 'SIGTERM');
|
|
368
|
+
state.clearPid(ctx.env);
|
|
369
|
+
}
|
|
370
|
+
const r = service.install(opts);
|
|
371
|
+
if (r.loaded) output.success(`已安装并启动:${r.file}`, ctx.flags);
|
|
372
|
+
else output.warn(`已写入 ${r.file},但自动加载失败,请手动加载(launchctl bootstrap / systemctl --user enable --now)`, ctx.flags);
|
|
373
|
+
return EXIT.OK;
|
|
374
|
+
}
|
|
375
|
+
if (action === 'uninstall') {
|
|
376
|
+
const r = service.uninstall();
|
|
377
|
+
output.success(r.existed ? `已卸载:${r.file}` : '没有安装过自启服务', ctx.flags);
|
|
378
|
+
return EXIT.OK;
|
|
379
|
+
}
|
|
380
|
+
throw new CliError(`未知动作:${action}`, EXIT.USAGE, { hint: '可用:install | uninstall | print' });
|
|
381
|
+
},
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
const enrollCmd = {
|
|
385
|
+
name: 'enroll',
|
|
386
|
+
summary: '(重新)登记本机,轮换设备令牌',
|
|
387
|
+
workspaceOptional: true,
|
|
388
|
+
principals: ['user'],
|
|
389
|
+
flags: { name: { type: 'string', summary: '设备显示名(缺省主机名)' } },
|
|
390
|
+
async run(ctx) {
|
|
391
|
+
requireUser(ctx);
|
|
392
|
+
const r = await enrollLib.enroll(ctx, { name: ctx.flags.name });
|
|
393
|
+
output.success(`已登记:${r.name}(${r.deviceId}),设备令牌存于${r.storage}`, ctx.flags);
|
|
394
|
+
return EXIT.OK;
|
|
395
|
+
},
|
|
396
|
+
};
|
|
397
|
+
|
|
398
|
+
module.exports = {
|
|
399
|
+
id: 'daemon',
|
|
400
|
+
summary: '本机守护进程:把本机 Claude Code / Codex / Pi 接入 DiWork 运行时',
|
|
401
|
+
description: [
|
|
402
|
+
'daemon 主动外连平台,本机不开端口;只在白名单目录内执行,危险操作回到 DiWork 页面审批。',
|
|
403
|
+
'',
|
|
404
|
+
'快速开始:',
|
|
405
|
+
' wd-cli auth login',
|
|
406
|
+
' wd-cli daemon start',
|
|
407
|
+
' cd ~/code/my-repo && wd-cli open # 把当前仓库加入白名单并作为项目打开',
|
|
408
|
+
].join('\n'),
|
|
409
|
+
principals: ['user'],
|
|
410
|
+
commands: [start, stop, status, logs, runtimesCmd, rootsCmd, executorCmd, serviceCmd, enrollCmd],
|
|
411
|
+
};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 运行时设备(/api/open/local-agents/devices):查看、改名、撤销本人登记的机器。
|
|
5
|
+
* 设备是个人资产,只作用于本人设备;撤销后该机 daemon 的设备令牌立即失效。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const http = require('../http');
|
|
9
|
+
const output = require('../output');
|
|
10
|
+
const dataInput = require('../data');
|
|
11
|
+
const { CliError, EXIT } = output;
|
|
12
|
+
const state = require('../daemon/state');
|
|
13
|
+
|
|
14
|
+
const COLUMNS = [
|
|
15
|
+
{ key: 'current', label: '' },
|
|
16
|
+
{ key: 'deviceId', label: '设备 ID' },
|
|
17
|
+
{ key: 'name', label: '名称' },
|
|
18
|
+
{ key: 'os', label: '系统' },
|
|
19
|
+
{ key: 'online', label: '在线' },
|
|
20
|
+
{ key: 'status', label: '状态' },
|
|
21
|
+
{ key: 'runtimes', label: '运行时' },
|
|
22
|
+
{ key: 'lastSeenAt', label: '最近在线' },
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
const deviceArg = { name: 'deviceId', required: true, summary: '设备 ID(wd-cli device list 查看)' };
|
|
26
|
+
|
|
27
|
+
const list = {
|
|
28
|
+
name: 'list',
|
|
29
|
+
summary: '列出我登记的设备',
|
|
30
|
+
workspaceOptional: true,
|
|
31
|
+
principals: ['user'],
|
|
32
|
+
async run(ctx) {
|
|
33
|
+
const items = (await http.request(ctx, { path: '/local-agents/devices' })) || [];
|
|
34
|
+
if (output.resolveFormat(ctx.flags) !== 'table' || ctx.flags.json || ctx.flags.jq) {
|
|
35
|
+
output.print(items, { flags: ctx.flags });
|
|
36
|
+
return EXIT.OK;
|
|
37
|
+
}
|
|
38
|
+
const self = state.deviceId(ctx.env);
|
|
39
|
+
output.print(items.map((d) => ({
|
|
40
|
+
current: d.deviceId === self ? '*' : '',
|
|
41
|
+
deviceId: d.deviceId,
|
|
42
|
+
name: d.name,
|
|
43
|
+
os: d.os,
|
|
44
|
+
online: d.online ? '在线' : '离线',
|
|
45
|
+
status: d.status === 'REVOKED' ? '已撤销' : '正常',
|
|
46
|
+
runtimes: (d.runtimes || []).filter((r) => r.available).map((r) => r.id).join(','),
|
|
47
|
+
lastSeenAt: d.lastSeenAt || '',
|
|
48
|
+
})), { flags: ctx.flags, columns: COLUMNS, empty: '还没有登记设备,执行 wd-cli daemon start 登记本机' });
|
|
49
|
+
return EXIT.OK;
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const rename = {
|
|
54
|
+
name: 'rename',
|
|
55
|
+
summary: '修改设备显示名',
|
|
56
|
+
workspaceOptional: true,
|
|
57
|
+
principals: ['user'],
|
|
58
|
+
args: [deviceArg, { name: 'name', required: true, summary: '新名称' }],
|
|
59
|
+
async run(ctx) {
|
|
60
|
+
const r = await http.request(ctx, {
|
|
61
|
+
method: 'PATCH',
|
|
62
|
+
path: `/local-agents/devices/${encodeURIComponent(ctx.args[0])}`,
|
|
63
|
+
body: { name: ctx.args[1] },
|
|
64
|
+
});
|
|
65
|
+
output.success(`已改名:${r && r.name}`, ctx.flags);
|
|
66
|
+
return EXIT.OK;
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const revoke = {
|
|
71
|
+
name: 'revoke',
|
|
72
|
+
summary: '撤销设备(其 daemon 立即断开,需重新登记才能再用)',
|
|
73
|
+
workspaceOptional: true,
|
|
74
|
+
principals: ['user'],
|
|
75
|
+
args: [deviceArg],
|
|
76
|
+
async run(ctx) {
|
|
77
|
+
const id = ctx.args[0];
|
|
78
|
+
const ok = await dataInput.confirm(`确认撤销设备 ${id}?`, ctx.flags);
|
|
79
|
+
if (!ok) throw new CliError('已取消', EXIT.USAGE);
|
|
80
|
+
await http.request(ctx, { method: 'DELETE', path: `/local-agents/devices/${encodeURIComponent(id)}` });
|
|
81
|
+
if (id === state.deviceId(ctx.env)) state.saveDeviceToken(ctx.runtime.profileName, null, ctx.env);
|
|
82
|
+
output.success(`已撤销:${id}`, ctx.flags);
|
|
83
|
+
return EXIT.OK;
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
module.exports = {
|
|
88
|
+
id: 'device',
|
|
89
|
+
summary: '运行时设备:查看 / 改名 / 撤销本人登记的机器',
|
|
90
|
+
principals: ['user'],
|
|
91
|
+
commands: [list, rename, revoke],
|
|
92
|
+
};
|