@dmall-inc/wd-cli 0.1.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.
@@ -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
+ };