@dmall-inc/wd-cli 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,463 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 技能:列出 / 搜索 / 版本 / 下载 / 上传 / 安装。
5
+ *
6
+ * 安装落地目录与 @dmall-inc/skills-cli 完全一致(同一套 agent 目标与备份规则),
7
+ * 这样两个工具装出来的东西在同一台机器上不会打架。
8
+ */
9
+
10
+ const fs = require('node:fs');
11
+ const os = require('node:os');
12
+ const path = require('node:path');
13
+ const { execFile } = require('node:child_process');
14
+ const { promisify } = require('node:util');
15
+
16
+ const http = require('../http');
17
+ const dataInput = require('../data');
18
+ const output = require('../output');
19
+ const { CliError, EXIT } = output;
20
+
21
+ const execFileAsync = promisify(execFile);
22
+
23
+ /** 安装目标:与 skills-cli 的 INSTALL_TARGETS 保持同名同路径。 */
24
+ const INSTALL_TARGETS = [
25
+ { id: 'universal', label: 'Universal', dir: () => path.join(os.homedir(), '.agents', 'skills') },
26
+ { id: 'claude-code', label: 'Claude Code', dir: () => path.join(os.homedir(), '.claude', 'skills') },
27
+ { id: 'codex', label: 'Codex', dir: () => path.join(os.homedir(), '.codex', 'skills') },
28
+ { id: 'openclaw', label: 'OpenClaw', dir: () => path.join(os.homedir(), '.openclaw', 'skills') },
29
+ { id: 'qoder', label: 'Qoder', dir: () => path.join(os.homedir(), '.qoder', 'skills') },
30
+ { id: 'hermes-agent', label: 'Hermes Agent', dir: () => path.join(os.homedir(), '.hermes', 'skills') },
31
+ ];
32
+
33
+ const LIST_COLUMNS = [
34
+ { key: 'id', label: 'ID' },
35
+ { key: 'name', label: '名称' },
36
+ { key: 'version', label: '版本' },
37
+ { key: 'skillType', label: '类型' },
38
+ { key: 'tag', label: '标签' },
39
+ { key: 'description', label: '简介' },
40
+ ];
41
+
42
+ const list = {
43
+ name: 'list',
44
+ summary: '列出当前工作空间可见的已发布技能',
45
+ flags: { q: { type: 'string', summary: '按名称 / 描述过滤' } },
46
+ examples: ['wd-cli skill list', 'wd-cli skill list --q 报表 --output json'],
47
+ async run(ctx) {
48
+ const items = (await http.request(ctx, { path: '/skills', query: { q: ctx.flags.q } })) || [];
49
+ output.print(items, { flags: ctx.flags, columns: LIST_COLUMNS, empty: '当前工作空间还没有已发布的技能' });
50
+ return EXIT.OK;
51
+ },
52
+ };
53
+
54
+ const search = {
55
+ name: 'search',
56
+ summary: '按关键词 / 归属搜索技能(分页)',
57
+ flags: {
58
+ q: { type: 'string', summary: '关键词,命中名称 / 描述 / 标签' },
59
+ scope: { type: 'string', summary: 'personal | team | company' },
60
+ page: { type: 'number', summary: '页码,从 1 开始' },
61
+ 'page-size': { type: 'number', summary: '每页条数(上限 100)' },
62
+ paginate: { type: 'boolean', summary: '自动翻页取全部' },
63
+ },
64
+ examples: ['wd-cli skill search --q python --scope personal', 'wd-cli skill search --q 报表 --paginate'],
65
+ async run(ctx) {
66
+ const options = {
67
+ path: '/skills/search',
68
+ query: {
69
+ q: ctx.flags.q,
70
+ scope: ctx.flags.scope,
71
+ pageNum: ctx.flags.page,
72
+ pageSize: ctx.flags.pageSize,
73
+ },
74
+ };
75
+ const result = ctx.flags.paginate
76
+ ? await http.requestAllPages(ctx, options)
77
+ : await http.request(ctx, options);
78
+ const rows = Array.isArray(result) ? result : result && result.list ? result.list : [];
79
+ output.print(ctx.flags.output === 'json' || ctx.flags.json || ctx.flags.jq ? result : rows, {
80
+ flags: ctx.flags,
81
+ columns: LIST_COLUMNS,
82
+ empty: '没有匹配的技能',
83
+ });
84
+ return EXIT.OK;
85
+ },
86
+ };
87
+
88
+ const versions = {
89
+ name: 'versions',
90
+ summary: '列出某技能的已发布版本',
91
+ args: [{ name: 'id', required: true, summary: '技能 id' }],
92
+ examples: ['wd-cli skill versions 123'],
93
+ async run(ctx) {
94
+ const items = (await http.request(ctx, { path: `/skills/${encodeURIComponent(ctx.args[0])}/versions` })) || [];
95
+ output.print(items, {
96
+ flags: ctx.flags,
97
+ columns: [
98
+ { key: 'versionLabel', label: '版本' },
99
+ { key: 'createdAt', label: '发布时间' },
100
+ { key: 'remark', label: '备注' },
101
+ ],
102
+ empty: '该技能尚未发布任何版本',
103
+ });
104
+ return EXIT.OK;
105
+ },
106
+ };
107
+
108
+ const download = {
109
+ name: 'download',
110
+ summary: '下载技能包(zip)',
111
+ args: [{ name: 'id', required: true, summary: '技能 id' }],
112
+ flags: {
113
+ version: { type: 'string', summary: '指定版本号,缺省为最新发布版本' },
114
+ out: { type: 'string', short: 'O', summary: '输出文件或目录,- 表示标准输出' },
115
+ },
116
+ examples: ['wd-cli skill download 123', 'wd-cli skill download 123 --version 2 -O ./skill-v2.zip'],
117
+ async run(ctx) {
118
+ const id = encodeURIComponent(ctx.args[0]);
119
+ const saved = await http.download(ctx, {
120
+ path: `/skills/${id}/download`,
121
+ query: { version: ctx.flags.version },
122
+ outPath: ctx.flags.out,
123
+ defaultName: `skill-${ctx.args[0]}.zip`,
124
+ });
125
+ if (saved.path !== '-') output.success(`已下载:${saved.path}(${saved.bytes} 字节)`, ctx.flags);
126
+ return EXIT.OK;
127
+ },
128
+ };
129
+
130
+ const importCmd = {
131
+ name: 'import',
132
+ summary: '上传技能包(zip)到平台',
133
+ args: [{ name: 'file', required: true, summary: '本地 zip 路径' }],
134
+ flags: {
135
+ 'skill-type': { type: 'string', summary: 'personal | team | company(缺省 personal)' },
136
+ name: { type: 'string', summary: '覆盖包内技能名' },
137
+ description: { type: 'string', summary: '覆盖简介' },
138
+ tag: { type: 'string', summary: '标签' },
139
+ },
140
+ examples: ['wd-cli skill import ./my-skill.zip --skill-type personal'],
141
+ async run(ctx) {
142
+ const form = http.buildFormData(
143
+ {
144
+ skillType: ctx.flags.skillType,
145
+ name: ctx.flags.name,
146
+ description: ctx.flags.description,
147
+ tag: ctx.flags.tag,
148
+ },
149
+ [{ name: 'file', path: ctx.args[0] }]
150
+ );
151
+ const created = await http.request(ctx, { method: 'POST', path: '/skills/import', form });
152
+ output.print(created, { flags: ctx.flags });
153
+ output.success(`已上传:${created && created.name ? created.name : ''}`, ctx.flags);
154
+ return EXIT.OK;
155
+ },
156
+ };
157
+
158
+ /** 解析安装引用:数字 id / @owner/name / https://host/skills/@owner/name。 */
159
+ function parseSkillRef(ref) {
160
+ const text = String(ref).trim();
161
+ if (/^\d+$/.test(text)) return { kind: 'id', id: text };
162
+ const at = text.match(/^@([^/]+)\/(.+)$/);
163
+ if (at) return { kind: 'ref', owner: at[1], name: at[2] };
164
+ if (/^https?:\/\//i.test(text)) {
165
+ let url;
166
+ try {
167
+ url = new URL(text);
168
+ } catch {
169
+ throw new CliError(`无法解析安装地址:${text}`, EXIT.USAGE);
170
+ }
171
+ const match = url.pathname.match(/\/skills\/@([^/]+)\/([^/]+)\/?$/);
172
+ if (!match) {
173
+ throw new CliError('安装地址不是 /skills/@owner/<name> 结构', EXIT.USAGE, {
174
+ hint: '也可直接用 wd-cli skill install @owner/name 或技能 id',
175
+ });
176
+ }
177
+ return { kind: 'ref', owner: decodeURIComponent(match[1]), name: decodeURIComponent(match[2]) };
178
+ }
179
+ throw new CliError(`无法识别的技能引用:${text}`, EXIT.USAGE, {
180
+ hint: '支持:技能 id、@owner/name、https://<host>/skills/@owner/<name>',
181
+ });
182
+ }
183
+
184
+ function resolveTargets(agentsFlag) {
185
+ if (!agentsFlag) return ['universal'];
186
+ const ids = String(agentsFlag)
187
+ .split(',')
188
+ .map((s) => s.trim())
189
+ .filter(Boolean);
190
+ const known = new Set(INSTALL_TARGETS.map((t) => t.id));
191
+ for (const id of ids) {
192
+ if (!known.has(id)) {
193
+ throw new CliError(`未知的安装目标:${id}`, EXIT.USAGE, {
194
+ hint: `可选:${INSTALL_TARGETS.map((t) => t.id).join(', ')}`,
195
+ });
196
+ }
197
+ }
198
+ return [...new Set(ids)];
199
+ }
200
+
201
+ async function unzipTo(zipPath, destDir) {
202
+ try {
203
+ await execFileAsync('unzip', ['-q', '-o', zipPath, '-d', destDir]);
204
+ } catch (error) {
205
+ if (error && error.code === 'ENOENT') {
206
+ throw new CliError('本机没有 unzip 命令', EXIT.USAGE, { hint: '先安装 unzip 再重试' });
207
+ }
208
+ throw new CliError(`解压失败:${error.message}`, EXIT.BUSINESS);
209
+ }
210
+ }
211
+
212
+ /** 解压产物可能多套一层目录:找到含 SKILL.md 的那一层。 */
213
+ function locateSkillRoot(dir) {
214
+ if (fs.existsSync(path.join(dir, 'SKILL.md'))) return dir;
215
+ const entries = fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory());
216
+ for (const entry of entries) {
217
+ const candidate = path.join(dir, entry.name);
218
+ if (fs.existsSync(path.join(candidate, 'SKILL.md'))) return candidate;
219
+ }
220
+ return null;
221
+ }
222
+
223
+ /** 重名先备份到同级 .backup/<name>-<时间戳>(与 skills-cli 同规则)。 */
224
+ function backupExisting(destination) {
225
+ if (!fs.existsSync(destination)) return null;
226
+ const parent = path.dirname(destination);
227
+ const backupDir = path.join(parent, '.backup');
228
+ fs.mkdirSync(backupDir, { recursive: true });
229
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
230
+ const backupPath = path.join(backupDir, `${path.basename(destination)}-${stamp}`);
231
+ fs.renameSync(destination, backupPath);
232
+ return backupPath;
233
+ }
234
+
235
+ const install = {
236
+ name: 'install',
237
+ summary: '安装技能到本地 agent 技能目录',
238
+ args: [{ name: 'ref', required: true, summary: '技能 id、@owner/name 或安装 URL' }],
239
+ flags: {
240
+ version: { type: 'string', summary: '指定版本号,缺省最新发布版本' },
241
+ agents: {
242
+ type: 'string',
243
+ summary: `安装目标,逗号分隔(${INSTALL_TARGETS.map((t) => t.id).join(', ')}),缺省 universal`,
244
+ },
245
+ 'target-dir': { type: 'string', summary: '直接指定安装目录,忽略 --agents' },
246
+ force: { type: 'boolean', summary: '同名目录直接覆盖,不做备份' },
247
+ },
248
+ examples: [
249
+ 'wd-cli skill install @team/report-generator',
250
+ 'wd-cli skill install 123 --agents universal,claude-code --yes',
251
+ ],
252
+ async run(ctx) {
253
+ const ref = parseSkillRef(ctx.args[0]);
254
+ let skillId = ref.kind === 'id' ? ref.id : null;
255
+ let skillName = ref.kind === 'ref' ? ref.name : null;
256
+
257
+ if (!skillId) {
258
+ const resolved = await http.request(ctx, {
259
+ path: '/skills/resolve',
260
+ query: { owner: ref.owner, name: ref.name },
261
+ });
262
+ if (!resolved || !resolved.id) {
263
+ throw new CliError(`技能不存在或当前工作空间不可见:@${ref.owner}/${ref.name}`, EXIT.BUSINESS);
264
+ }
265
+ skillId = String(resolved.id);
266
+ skillName = resolved.name || ref.name;
267
+ }
268
+
269
+ const targets = ctx.flags.targetDir
270
+ ? [{ id: 'custom', label: '自定义目录', dir: () => path.dirname(path.resolve(ctx.flags.targetDir)) }]
271
+ : resolveTargets(ctx.flags.agents).map((id) => INSTALL_TARGETS.find((t) => t.id === id));
272
+
273
+ const destinations = ctx.flags.targetDir
274
+ ? [path.resolve(ctx.flags.targetDir)]
275
+ : targets.map((t) => path.join(t.dir(), skillName || `skill-${skillId}`));
276
+
277
+ if (!ctx.flags.yes && output.isTty(process.stdin)) {
278
+ output.info(`将安装到:\n${destinations.map((d) => ` ${d}`).join('\n')}`, ctx.flags);
279
+ const ok = await dataInput.confirm('确认继续?', ctx.flags);
280
+ if (!ok) {
281
+ output.info('已取消', ctx.flags);
282
+ return EXIT.OK;
283
+ }
284
+ }
285
+
286
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wd-cli-skill-'));
287
+ const zipPath = path.join(tmpDir, 'skill.zip');
288
+ try {
289
+ await http.download(ctx, {
290
+ path: `/skills/${encodeURIComponent(skillId)}/download`,
291
+ query: { version: ctx.flags.version },
292
+ outPath: zipPath,
293
+ });
294
+ const extractDir = path.join(tmpDir, 'extract');
295
+ fs.mkdirSync(extractDir, { recursive: true });
296
+ await unzipTo(zipPath, extractDir);
297
+ const skillRoot = locateSkillRoot(extractDir);
298
+ if (!skillRoot) {
299
+ throw new CliError('技能包里没有找到 SKILL.md,无法安装', EXIT.BUSINESS);
300
+ }
301
+
302
+ const installed = [];
303
+ for (const destination of destinations) {
304
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
305
+ if (fs.existsSync(destination)) {
306
+ if (ctx.flags.force) fs.rmSync(destination, { recursive: true, force: true });
307
+ else {
308
+ const backup = backupExisting(destination);
309
+ if (backup) output.info(`已备份旧版本到 ${backup}`, ctx.flags);
310
+ }
311
+ }
312
+ fs.cpSync(skillRoot, destination, { recursive: true });
313
+ if (!fs.existsSync(path.join(destination, 'SKILL.md'))) {
314
+ throw new CliError(`安装后校验失败:${destination} 内没有 SKILL.md`, EXIT.BUSINESS);
315
+ }
316
+ installed.push(destination);
317
+ }
318
+ output.print(
319
+ installed.map((dir) => ({ skill: skillName || skillId, path: dir })),
320
+ { flags: ctx.flags, columns: [{ key: 'skill', label: '技能' }, { key: 'path', label: '安装位置' }] }
321
+ );
322
+ output.success(`已安装 ${skillName || skillId} 到 ${installed.length} 个目录`, ctx.flags);
323
+ return EXIT.OK;
324
+ } finally {
325
+ fs.rmSync(tmpDir, { recursive: true, force: true });
326
+ }
327
+ },
328
+ };
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
+
451
+ module.exports = {
452
+ id: 'skill',
453
+ summary: '技能:列出 / 搜索 / 下载 / 安装 / 上传 / 原地升级',
454
+ description: '安装目录与 @dmall-inc/skills-cli 一致;令牌直连模式下需要 wat_ 工作空间令牌。',
455
+ principals: ['workspace'],
456
+ commands: [list, search, versions, download, importCmd, install, upgrade, updateFile],
457
+ parseSkillRef,
458
+ resolveTargets,
459
+ backupExisting,
460
+ locateSkillRoot,
461
+ INSTALL_TARGETS,
462
+ };
463
+
@@ -0,0 +1,110 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * 工作空间切换(模型对标 kubectl 的 context:list / use / current)。
5
+ *
6
+ * 选定的工作空间写进 profile,之后每个资源请求都带 X-Workspace-Id;
7
+ * 想只影响一次调用就加 --workspace <id>,配置不变。
8
+ */
9
+
10
+ const config = require('../config');
11
+ const http = require('../http');
12
+ const output = require('../output');
13
+ const { CliError, EXIT } = output;
14
+
15
+ const COLUMNS = [
16
+ { key: 'current', label: '' },
17
+ { key: 'id', label: 'ID' },
18
+ { key: 'name', label: '名称' },
19
+ { key: 'role', label: '角色' },
20
+ { key: 'status', label: '状态' },
21
+ ];
22
+
23
+ async function fetchWorkspaces(ctx) {
24
+ return http.request(ctx, { method: 'GET', path: '/workspaces' });
25
+ }
26
+
27
+ const list = {
28
+ name: 'list',
29
+ summary: '列出我所属的工作空间',
30
+ examples: ['wd-cli workspace list', 'wd-cli workspace list --output json'],
31
+ workspaceOptional: true,
32
+ principals: ['user'],
33
+ async run(ctx) {
34
+ const items = (await fetchWorkspaces(ctx)) || [];
35
+ const currentId = ctx.runtime.workspaceId;
36
+ const rows = items.map((item) => ({
37
+ current: String(item.id) === String(currentId) ? '*' : '',
38
+ id: item.id,
39
+ name: item.name,
40
+ role: item.role,
41
+ status: item.status,
42
+ }));
43
+ output.print(rows, {
44
+ flags: ctx.flags,
45
+ columns: COLUMNS,
46
+ empty: '你还不属于任何工作空间,请联系工作空间管理员邀请你加入',
47
+ });
48
+ if (!currentId && rows.length) {
49
+ output.info('用 wd-cli workspace use <id> 选定当前工作空间', ctx.flags);
50
+ }
51
+ return EXIT.OK;
52
+ },
53
+ };
54
+
55
+ const use = {
56
+ name: 'use',
57
+ summary: '选定当前工作空间',
58
+ args: [{ name: 'id|name', required: true, summary: '工作空间 id 或名称' }],
59
+ examples: ['wd-cli workspace use 42', 'wd-cli workspace use 数据组'],
60
+ workspaceOptional: true,
61
+ principals: ['user'],
62
+ async run(ctx) {
63
+ const wanted = String(ctx.args[0]);
64
+ const items = (await fetchWorkspaces(ctx)) || [];
65
+ const matched =
66
+ items.find((item) => String(item.id) === wanted) ||
67
+ items.find((item) => item.name === wanted) ||
68
+ null;
69
+ if (!matched) {
70
+ throw new CliError(`不是工作空间 ${wanted} 的成员,或该工作空间不存在`, EXIT.USAGE, {
71
+ hint: '用 wd-cli workspace list 看可选的工作空间',
72
+ });
73
+ }
74
+ config.updateProfile(
75
+ ctx.runtime.profileName,
76
+ { workspaceId: String(matched.id), workspaceName: matched.name },
77
+ ctx.env
78
+ );
79
+ output.success(`当前工作空间:${matched.name}(id ${matched.id},角色 ${matched.role})`, ctx.flags);
80
+ return EXIT.OK;
81
+ },
82
+ };
83
+
84
+ const current = {
85
+ name: 'current',
86
+ summary: '显示当前工作空间',
87
+ examples: ['wd-cli workspace current'],
88
+ workspaceOptional: true,
89
+ skipPrincipalCheck: true,
90
+ async run(ctx) {
91
+ if (!ctx.runtime.workspaceId) {
92
+ output.warn('尚未选定工作空间:wd-cli workspace use <id>', ctx.flags);
93
+ return EXIT.USAGE;
94
+ }
95
+ output.print(
96
+ { id: ctx.runtime.workspaceId, name: ctx.runtime.workspaceName || '' },
97
+ { flags: ctx.flags }
98
+ );
99
+ return EXIT.OK;
100
+ },
101
+ };
102
+
103
+ module.exports = {
104
+ id: 'workspace',
105
+ summary: '工作空间:列出 / 切换 / 查看当前',
106
+ description:
107
+ '资源可见性由「当前用户 × 当前工作空间」决定。切换工作空间就是切换你能看到的技能、知识库、应用。',
108
+ principals: ['user'],
109
+ commands: [list, use, current],
110
+ };