-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.js
More file actions
459 lines (448 loc) · 26.9 KB
/
Copy pathplugin.js
File metadata and controls
459 lines (448 loc) · 26.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// dsh-github-plugin-tools — 合并插件:GitHub ↔ DSH 插件管理工具集
// 合并自 install-github-plugin + upload-github-plugin + uninstall-github-plugin,
// 注册三个工具(工具名与合并前一致,调用方式不变):
// install_github_plugin — 下载/校验/留档 GitHub 插件(包装 install-github-plugin.ps1)
// upload_github_plugin — 本地插件上传 GitHub(包装 upload-github-plugin.js)
// uninstall_dsh_plugin — 三维卸载(动态/预设/工作区)
// 注:预设持久化版本,__PRESET_DIR 由包装器注入,作为脚本查找回退目录。
return {
name: 'dsh-github-plugin-tools',
inject: ['dynamicCordisRunner'],
apply(ctx) {
const fsSvc = ctx.get('fs');
const shellSvc = ctx.get('shell');
const policySvc = ctx.get('sandboxPolicy');
const agentPresets = ctx.get('agentPresets');
// ================= 共享工具函数 =================
function sessionCwdOf(agent) {
try { return agent && agent.session && agent.session.header ? agent.session.header.cwd : undefined; } catch (e) { return undefined; }
}
function standingPolicyFor(agent) {
try {
return policySvc && typeof policySvc.resolve === 'function'
? policySvc.resolve(agent && agent.session ? { session: agent.session } : {})
: undefined;
} catch (e) { return undefined; }
}
function q(s) { return "'" + String(s).replace(/'/g, "''") + "'"; }
async function findScript(name, sessionCwd) {
const candidates = [];
if (sessionCwd) candidates.push(sessionCwd);
if (typeof __PRESET_DIR === 'string' && __PRESET_DIR) candidates.push(__PRESET_DIR);
for (const base of candidates) {
try {
const t = await fsSvc.resolve(name, { cwd: base });
return fsSvc.processPath ? fsSvc.processPath(t) : String(t.path || t);
} catch (e) { /* next */ }
}
return '';
}
function absJoin(sessionCwd, p) {
if (/^[a-zA-Z]:[\\/]|^\\\\/.test(p)) return p;
return (sessionCwd || '') + '\\' + p.replace(/^[\\/]+/, '');
}
async function runShellCommand(cmd, standingPolicy, timeoutMs, stdoutMaxBytes) {
const spec = shellSvc.resolve({ command: cmd, timeoutMs: timeoutMs, stdoutMaxBytes: stdoutMaxBytes });
if (standingPolicy) spec.sandboxPolicy = standingPolicy;
return await shellSvc.run(spec);
}
function parseMarker(outText, marker) {
let parsed = null;
const lines = outText.split(/\r?\n/);
for (let i = lines.length - 1; i >= 0; i--) {
const idx = lines[i].indexOf(marker);
if (idx !== -1) {
try { parsed = JSON.parse(lines[i].slice(idx + marker.length)); break; } catch (e) { /* next */ }
}
}
const human = lines.filter(function (l) { return l.indexOf(marker) === -1; }).join('\n').trim();
return { parsed: parsed, human: human };
}
function registerToolSafely(tool, altName, logTag) {
try {
harness.registerTool(ctx, tool);
} catch (e) {
tool.name = altName;
try {
harness.registerTool(ctx, tool);
} catch (e2) {
console.error(logTag + ': tool registration failed: ' + String(e2 && e2.message ? e2.message : e2));
}
}
}
// ================= 工具 1: install_github_plugin =================
const installTool = harness.defineTool({
name: 'install_github_plugin',
description: '通用 GitHub → DSH 插件安装器。输入 GitHub 仓库 URL,自动完成:1) 下载仓库 zip(优先 Node fetch,绕过本机 schannel TLS 失败 / hosts 拦截 GitHub 域名的问题;备用 curl);2) 解压并定位 plugin.js(或 *.plugin.js);3) 校验(含 return { 插件对象形态 + Node 语法编译);4) 源码留档到 <out_dir>/<repo>/(plugin.js + README + install-info.json)。返回结构化结果;拿到结果后把留档的 plugin.js 全文作为 code.host 交给 cordis_define(idPrefix 3-6 位小写字母)再 cordis_run 即完成插件注册。',
parameters: {
repo_url: { type: 'string', required: true, description: 'GitHub 仓库 URL,如 https://github.com/owner/repo' },
out_dir: { type: 'string', description: '源码留档目录(绝对或相对;默认会话工作区 plugins/)' },
branch: { type: 'string', description: '指定分支(默认自动尝试 main → master)' }
},
output: {
schema: {
type: 'object',
additionalProperties: false,
properties: {
ok: { type: 'boolean', required: true },
repo: { type: 'string' },
owner: { type: 'string' },
branch: { type: 'string' },
downloaded: { type: 'string' },
bytes: { type: 'integer' },
zipPath: { type: 'string' },
pluginFiles: { type: 'array', items: { type: 'string' } },
validated: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { rel: { type: 'string' }, hasReturnPlugin: { type: 'boolean' }, compiles: { type: 'boolean' }, error: { type: 'string' } } } },
archivedDir: { type: 'string' },
errors: { type: 'array', items: { type: 'string' } },
human: { type: 'string' },
exit_code: { type: 'integer' }
}
},
render(args, value) {
const lines = [];
if (value.ok) {
lines.push('📦 下载完成: ' + (value.owner || '') + '/' + (value.repo || '') + ' [' + (value.branch || '') + '] via ' + (value.downloaded || '') + ' (' + (value.bytes || 0) + ' bytes)');
for (const v of (value.validated || [])) {
const flags = (v.hasReturnPlugin ? 'return{✓ ' : 'return{✗ ') + (v.compiles ? '编译✓' : '编译✗');
lines.push('- ' + v.rel + ': ' + flags);
}
lines.push('- 源码留档: ' + (value.archivedDir || ''));
lines.push('下一步: 把 ' + (value.archivedDir || '') + '\\plugin.js 全文作为 code.host 交给 cordis_define,再 cordis_run 完成注册');
} else {
lines.push('❌ 安装失败: ' + ((value.errors || []).join('; ') || '未知错误'));
}
if (value.human) lines.push(value.human);
return [{ type: 'text', text: lines.join('\n') }];
}
},
timeoutMs: 10 * 60 * 1000,
isConcurrencySafe: () => false,
async execute(args, exec) {
const agent = exec && exec.agent ? exec.agent : null;
const sessionCwd = sessionCwdOf(agent);
if (!fsSvc || !shellSvc) return { ok: false, errors: ['fs/shell 服务不可用'], human: '' };
const scriptPath = await findScript('install-github-plugin.ps1', sessionCwd);
if (!scriptPath) return { ok: false, errors: ['未找到 install-github-plugin.ps1(应位于会话工作区根目录或预设目录)'], human: '' };
let outDir;
const rawOut = typeof args.out_dir === 'string' && args.out_dir.trim() ? args.out_dir.trim() : '';
if (!rawOut) outDir = (sessionCwd || '') + '\\plugins';
else outDir = absJoin(sessionCwd, rawOut);
const standingPolicy = standingPolicyFor(agent);
const branchArg = typeof args.branch === 'string' && args.branch.trim() ? ' -Branch ' + q(args.branch.trim()) : '';
const cmd = "$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; & " + q(scriptPath) + ' -RepoUrl ' + q(args.repo_url) + ' -OutDir ' + q(outDir) + branchArg + ' -Json';
const res = await runShellCommand(cmd, standingPolicy, 600000, 8000000);
const outText = res && res.stdout && typeof res.stdout.text === 'string' ? res.stdout.text : '';
const stderrText = res && res.stderr && typeof res.stderr.text === 'string' ? res.stderr.text : '';
const mk = parseMarker(outText, '__INSTALL_JSON__');
if (!mk.parsed) {
return { ok: false, errors: ['安装脚本输出解析失败' + (res && res.exitCode !== undefined ? '(exit ' + res.exitCode + ')' : '')], human: mk.human || stderrText || '' };
}
mk.parsed.human = mk.human;
mk.parsed.exit_code = res ? res.exitCode : undefined;
if (!mk.parsed.errors) mk.parsed.errors = [];
return mk.parsed;
}
});
registerToolSafely(installTool, 'install_github_plugin2', 'dsh-github-tools:install');
// ================= 工具 2: upload_github_plugin =================
const uploadTool = harness.defineTool({
name: 'upload_github_plugin',
description: '把本地 DSH 插件(插件目录/文件)上传到 GitHub 仓库。本机 schannel TLS 损坏且 hosts 拦截 github.com/api.github.com,此工具全程走 Node OpenSSL + 自定义 lookup 钉住真实 IP(经国内 DoH 解析),不依赖 git/curl。流程:检查仓库(可选自动创建,auto_init)→ 收集 plugin_dir 内文本文件(或 files 显式列表)→ 经 Contents API 逐个 PUT(base64,存在则带 sha 增量更新;内容一致自动跳过)。认证:GitHub PAT(fine-grained 需目标仓库 Contents 读写权限;classic 需 repo 权限)。token 只经环境变量传入,不进命令行,用完即删。check=true 时只检查连通性与仓库状态,无需 token。',
parameters: {
repo: { type: 'string', required: true, description: 'owner/repo 或 GitHub 仓库 URL' },
token: { type: 'string', description: 'GitHub Personal Access Token(check 模式不需要)' },
plugin_dir: { type: 'string', description: '本地插件目录(绝对或相对;默认会话工作区 plugins/<仓库名>)' },
files: { type: 'array', items: { type: 'string' }, description: '显式上传文件列表(相对 plugin_dir 的路径;默认自动收集文本文件)' },
branch: { type: 'string', description: '目标分支(默认仓库默认分支;不存在时 Contents API 会自动创建)' },
message: { type: 'string', description: '提交信息(默认 Update plugin via dsh uploader)' },
private: { type: 'boolean', description: '自动创建仓库时设为私有(默认公开)' },
create: { type: 'boolean', description: '仓库不存在时自动创建(默认 true)' },
check: { type: 'boolean', description: '只检查连通性与仓库状态,不上传、不需要 token(默认 false)' }
},
output: {
schema: {
type: 'object',
additionalProperties: false,
properties: {
ok: { type: 'boolean', required: true },
owner: { type: 'string' },
repo: { type: 'string' },
branch: { type: 'string' },
repo_status: { type: 'string' },
created_repo: { type: 'boolean' },
dns: { type: 'string' },
check: { type: 'boolean' },
files: { type: 'array', items: { type: 'string' } },
uploaded: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { path: { type: 'string' }, status: { type: 'string' }, sha: { type: 'string' } } } },
message: { type: 'string' },
errors: { type: 'array', items: { type: 'string' } },
human: { type: 'string' },
exit_code: { type: 'integer' }
}
},
render(args, value) {
const lines = [];
if (value.ok) {
lines.push('📤 上传完成: ' + (value.owner || '') + '/' + (value.repo || '') + ' [' + (value.branch || '') + ']' + (value.created_repo ? '(新建仓库)' : ''));
if (value.repo_status === 'missing') lines.push('- 仓库不存在(上传时会自动创建)');
if (value.uploaded && value.uploaded.length) {
for (const f of value.uploaded) lines.push('- ' + f.status + ' ' + f.path);
lines.push('- 共 ' + value.uploaded.length + ' 个文件');
}
if (value.message) lines.push('- ' + value.message);
} else {
lines.push('❌ 上传失败: ' + ((value.errors || []).join('; ') || '未知错误'));
}
if (value.human) lines.push(value.human);
return [{ type: 'text', text: lines.join('\n') }];
}
},
timeoutMs: 10 * 60 * 1000,
isConcurrencySafe: () => false,
async execute(args, exec) {
const agent = exec && exec.agent ? exec.agent : null;
const sessionCwd = sessionCwdOf(agent);
if (!fsSvc || !shellSvc) return { ok: false, errors: ['fs/shell 服务不可用'], human: '' };
const checkMode = args.check === true;
const repoRaw = typeof args.repo === 'string' ? args.repo.trim() : '';
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repoRaw.replace(/^https?:\/\/github\.com\//i, '').replace(/\.git$/, '').replace(/^\/+|\/+$/g, ''))) {
return { ok: false, errors: ['repo 必须是 owner/repo 形式(或 GitHub URL)'], human: '' };
}
const cleanRepo = repoRaw.replace(/^https?:\/\/github\.com\//i, '').replace(/\.git$/, '').replace(/^\/+|\/+$/g, '');
const repoName = cleanRepo.split('/').pop() || '';
if (!checkMode && !(typeof args.token === 'string' && args.token.trim())) {
return { ok: false, errors: ['上传模式需要 GitHub token(check 模式无需)'], human: '' };
}
const scriptPath = await findScript('upload-github-plugin.js', sessionCwd);
if (!scriptPath) return { ok: false, errors: ['未找到 upload-github-plugin.js(应位于会话工作区根目录或预设目录)'], human: '' };
let pluginDir;
const rawDir = typeof args.plugin_dir === 'string' && args.plugin_dir.trim() ? args.plugin_dir.trim() : '';
if (!rawDir) {
if (!repoName) return { ok: false, errors: ['无法从 repo 推导插件目录名,请显式传 plugin_dir'], human: '' };
pluginDir = (sessionCwd || '') + '\\plugins\\' + repoName;
} else {
pluginDir = absJoin(sessionCwd, rawDir);
}
const standingPolicy = standingPolicyFor(agent);
let tokenFile = '';
if (!checkMode) {
const ts = Date.now();
try {
const tf = await fsSvc.resolve('.gh-upload-' + ts + '.token', sessionCwd ? { cwd: sessionCwd } : {});
await fsSvc.writeText(tf, String(args.token).trim(), undefined, undefined, standingPolicy);
tokenFile = fsSvc.processPath ? fsSvc.processPath(tf) : String(tf.path || tf);
} catch (e) {
return { ok: false, errors: ['写入 token 临时文件失败: ' + (e && e.message ? e.message : String(e))], human: '' };
}
}
let cmd = "$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ";
if (tokenFile) cmd += "$env:GH_PLUGIN_TOKEN = (Get-Content -Raw " + q(tokenFile) + ").Trim(); ";
cmd += "node " + q(scriptPath) + " --repo " + q(cleanRepo) + " --plugin-dir " + q(pluginDir);
if (checkMode) cmd += " --check";
if (typeof args.branch === 'string' && args.branch.trim()) cmd += " --branch " + q(args.branch.trim());
if (typeof args.message === 'string' && args.message.trim()) cmd += " --message " + q(args.message.trim());
if (args.private === true) cmd += " --private";
if (args.create === false) cmd += " --no-create";
if (Array.isArray(args.files) && args.files.length) cmd += " --files " + q(args.files.join(','));
cmd += "; $code = $LASTEXITCODE";
if (tokenFile) cmd += "; Remove-Item -LiteralPath " + q(tokenFile) + " -Force -ErrorAction SilentlyContinue";
cmd += "; exit $code";
const res = await runShellCommand(cmd, standingPolicy, 600000, 8000000);
const outText = res && res.stdout && typeof res.stdout.text === 'string' ? res.stdout.text : '';
const stderrText = res && res.stderr && typeof res.stderr.text === 'string' ? res.stderr.text : '';
const mk = parseMarker(outText, '__UPLOAD_JSON__');
if (!mk.parsed) {
return { ok: false, errors: ['上传脚本输出解析失败' + (res && res.exitCode !== undefined ? '(exit ' + res.exitCode + ')' : '')], human: mk.human || stderrText || '' };
}
mk.parsed.human = mk.human;
mk.parsed.exit_code = res ? res.exitCode : undefined;
if (!mk.parsed.errors) mk.parsed.errors = [];
return mk.parsed;
}
});
registerToolSafely(uploadTool, 'upload_github_plugin2', 'dsh-github-tools:upload');
// ================= 工具 3: uninstall_dsh_plugin =================
// 内置插件登记表:别名 → 卸载目标
// 注:三个 GitHub 工具已合并为一个插件(dsh-github-plugin-tools),
// 卸载 install/upload/uninstall 任一别名即卸载整个工具集。
// 动态插件在注册表中的 name 是"包名"(如 xxx v1),动态维度按别名前缀匹配包名。
const PLUGINS = {
'ws-cleaner': {
aliases: ['ws-cleaner', 'ws_cleaner', 'clean_workspace'],
rowId: 'plugin-ws-cleaner',
presetFiles: ['plugins/ws-cleaner.js', 'plugins/body/ws-cleaner.js'],
workspacePaths: ['plugins/ws-cleaner'],
},
'wiki-to-ima': {
aliases: ['imakb', 'wiki-to-ima', 'wiki_to_ima'],
rowId: 'plugin-wiki-to-ima',
presetFiles: ['plugins/imakb.js', 'plugins/body/imakb.js'],
workspacePaths: ['plugins/imakb'],
},
'dsh-github-plugin-tools': {
aliases: ['install-github-plugin', 'install_github_plugin', 'installer', 'dsh-installer',
'upload-github-plugin', 'upload_github_plugin', 'uploader', 'dsh-uploader',
'uninstall-github-plugin', 'uninstall_dsh_plugin', 'uninstaller', 'dsh-uninstaller',
'github-tools', 'dsh-github-tools'],
rowId: 'plugin-github-tools',
presetFiles: ['plugins/github-tools.js', 'plugins/body/github-tools.js',
'install-github-plugin.ps1', 'upload-github-plugin.js',
'plugins/install-github-plugin.js', 'plugins/body/install-github-plugin.js',
'plugins/upload-github-plugin.js', 'plugins/body/upload-github-plugin.js',
'plugins/uninstall-github-plugin.js', 'plugins/body/uninstall-github-plugin.js'],
workspacePaths: ['plugins/dsh-github-tools', 'plugins/install-github-plugin', 'plugins/upload-github-plugin', 'plugins/uninstall-github-plugin', 'install-github-plugin.ps1', 'upload-github-plugin.js'],
},
};
const uninstallTool = harness.defineTool({
name: 'uninstall_dsh_plugin',
description: '卸载一个 DSH 插件(按名称/别名或动态插件 pluginId)。三种卸载维度:dynamic=撤销会话内动态插件(经 dynamicCordisRunner.undefine);preset=从用户预设 dsh-plugins 移除组合行并删除包装器/函数体/附属脚本;workspace=删除工作区 plugins/<name>/ 留档与根目录附属脚本。默认 scope=all 一次全清;dry_run=true 时只列出将要执行的动作不实际删除。支持的插件:ws-cleaner(clean_workspace)、wiki-to-ima(imakb)、dsh-github-plugin-tools(即 install_github_plugin / upload_github_plugin / uninstall_dsh_plugin 三个 GitHub 工具的合并插件,卸载任一别名即卸载整个工具集)。注意:卸载持久化插件后需重启/新开会话才完全生效;本工具不会删除 GitHub 上的仓库。',
parameters: {
plugin: { type: 'string', required: true, description: '插件名称/别名(如 imakb、wiki_to_ima、ws-cleaner、installer、uploader、uninstaller、github-tools)或动态插件 pluginId(如 clean-1)' },
scope: { type: 'string', description: '卸载维度: all(默认) | dynamic | preset | workspace' },
dry_run: { type: 'boolean', description: '为 true 时只列出将执行的动作,不实际删除(默认 false)' }
},
output: {
schema: {
type: 'object',
additionalProperties: false,
properties: {
ok: { type: 'boolean', required: true },
target: { type: 'string' },
dry_run: { type: 'boolean', required: true },
removed_dynamic: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { pluginId: { type: 'string' }, name: { type: 'string' } } } },
removed_preset: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { preset: { type: 'string' }, row: { type: 'string' }, files: { type: 'array', items: { type: 'string' } } } } },
removed_workspace: { type: 'array', items: { type: 'string' } },
errors: { type: 'array', items: { type: 'string' } }
}
},
render(args, value) {
const lines = [];
if (value.dry_run) lines.push('🔍 卸载预览(dry_run,未实际删除): ' + (value.target || ''));
else lines.push('🗑️ 卸载完成: ' + (value.target || ''));
if (value.removed_dynamic && value.removed_dynamic.length) {
for (const d of value.removed_dynamic) lines.push('- 动态插件: ' + d.pluginId + ' (' + d.name + ')');
}
if (value.removed_preset && value.removed_preset.length) {
for (const p of value.removed_preset) {
lines.push('- 预设行: ' + p.row + ' (' + p.preset + ')');
for (const f of p.files) lines.push(' · 删除文件: ' + f);
}
}
if (value.removed_workspace && value.removed_workspace.length) {
for (const w of value.removed_workspace) lines.push('- 工作区: ' + w);
}
if (value.errors && value.errors.length) lines.push('- 注意: ' + value.errors.join('; '));
return [{ type: 'text', text: lines.join('\n') }];
}
},
timeoutMs: 5 * 60 * 1000,
isConcurrencySafe: () => false,
async execute(args, exec) {
const agent = exec && exec.agent ? exec.agent : null;
const sessionCwd = sessionCwdOf(agent);
const dryRun = args.dry_run === true;
const scope = (typeof args.scope === 'string' && args.scope.trim()) ? args.scope.trim() : 'all';
const input = String(args.plugin || '').trim();
const result = { ok: true, target: input, dry_run: dryRun, removed_dynamic: [], removed_preset: [], removed_workspace: [], errors: [] };
// 1. 解析目标
let entryKey = '';
if (input) {
for (const key of Object.keys(PLUGINS)) {
const e = PLUGINS[key];
const names = [key, e.rowId].concat(e.aliases);
if (names.some((n) => n && n.toLowerCase() === input.toLowerCase())) { entryKey = key; break; }
}
}
let dynamicIds = [];
try {
const list = ctx.dynamicCordisRunner.listPlugins(agent);
for (const p of list) {
const pname = String(p.name || '').toLowerCase();
if (p.pluginId === input || pname === input.toLowerCase()) dynamicIds.push(p.pluginId);
else if (entryKey) {
const cands = [entryKey].concat(PLUGINS[entryKey].aliases);
for (const c of cands) {
const cl = String(c || '').toLowerCase();
if (!cl) continue;
if (pname === cl || pname.indexOf(cl + ' ') === 0) { dynamicIds.push(p.pluginId); break; }
}
}
}
} catch (e) {
result.errors.push('读取动态插件列表失败: ' + (e && e.message ? e.message : String(e)));
}
dynamicIds = Array.from(new Set(dynamicIds));
if (!entryKey && dynamicIds.length === 0) {
result.ok = false;
result.errors.push('未识别的插件: "' + input + '"(可用名称: ws-cleaner / wiki-to-ima(imakb) / dsh-github-plugin-tools(installer / uploader / uninstaller / github-tools),或动态插件 pluginId)');
return result;
}
const entry = entryKey ? PLUGINS[entryKey] : null;
const standingPolicy = standingPolicyFor(agent);
// 2. dynamic 维度
if (scope === 'all' || scope === 'dynamic') {
for (const id of dynamicIds) {
let name = id;
try {
const ref = ctx.dynamicCordisRunner.reference(agent, id);
if (ref && ref.name) name = ref.name;
} catch (e) { /* keep id */ }
if (dryRun) { result.removed_dynamic.push({ pluginId: id, name: name }); continue; }
try {
await ctx.dynamicCordisRunner.undefine(agent, id);
result.removed_dynamic.push({ pluginId: id, name: name });
} catch (e) {
result.errors.push('撤销动态插件失败 ' + id + ': ' + (e && e.message ? e.message : String(e)));
}
}
}
// 3. preset 维度
if (entry && (scope === 'all' || scope === 'preset')) {
try {
const resolved = await agentPresets.resolve('dsh-plugins');
const ymlPath = resolved && resolved.path ? resolved.path : '';
if (!ymlPath) throw new Error('未找到 dsh-plugins 预设');
const sep = ymlPath.lastIndexOf('\\') !== -1 ? '\\' : '/';
const presetDir = ymlPath.slice(0, ymlPath.lastIndexOf(sep));
const ymlTarget = await fsSvc.resolve(ymlPath);
const text = await fsSvc.readText(ymlTarget);
const rowRe = new RegExp('\\n?- id: ' + entry.rowId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\r?\\n\\s*name: [^\\n]*', 'g');
const nextText = text.replace(rowRe, '');
const files = [];
for (const rel of entry.presetFiles) files.push(presetDir + sep + rel.replace(/\//g, sep));
const removedFiles = [];
if (!dryRun) {
await fsSvc.writeText(ymlTarget, nextText, undefined, undefined, standingPolicy);
if (shellSvc) {
const delCmd = files.map((f) => "Remove-Item -LiteralPath '" + String(f).replace(/'/g, "''") + "' -Recurse -Force -ErrorAction SilentlyContinue").join('; ');
await runShellCommand("$ErrorActionPreference='SilentlyContinue'; " + delCmd, standingPolicy, 120000, 100000);
}
}
for (const f of files) removedFiles.push(f);
result.removed_preset.push({ preset: 'dsh-plugins', row: entry.rowId, files: removedFiles });
} catch (e) {
result.errors.push('卸载预设行失败: ' + (e && e.message ? e.message : String(e)));
}
}
// 4. workspace 维度
if (entry && (scope === 'all' || scope === 'workspace')) {
const base = sessionCwd || '';
for (const rel of entry.workspacePaths) {
const abs = base ? base + '\\' + rel.replace(/\//g, '\\') : rel;
result.removed_workspace.push(abs);
if (!dryRun && shellSvc) {
try {
await runShellCommand("$ErrorActionPreference='SilentlyContinue'; Remove-Item -LiteralPath '" + String(abs).replace(/'/g, "''") + "' -Recurse -Force -ErrorAction SilentlyContinue", standingPolicy, 120000, 100000);
} catch (e) {
result.errors.push('删除工作区失败 ' + abs + ': ' + (e && e.message ? e.message : String(e)));
}
}
}
}
return result;
}
});
registerToolSafely(uninstallTool, 'uninstall_dsh_plugin2', 'dsh-github-tools:uninstall');
}
};