dsh-plugin-trim 0.2.5 → 0.2.6

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 CHANGED
@@ -7,13 +7,13 @@ DSH 插件生态的**减负**与**兼容性体检**插件。
7
7
  从 npm 安装(推荐):
8
8
 
9
9
  ```bash
10
- dsh plugin --profile web add dsh-plugin-trim@0.2.5
10
+ dsh plugin --profile web add dsh-plugin-trim@0.2.6
11
11
  ```
12
12
 
13
13
  从 GitHub Release 安装(备用,无需 npm):
14
14
 
15
15
  ```bash
16
- dsh plugin --profile web add "https://github.com/Starlit-Sky-code/dsh-experience-optimizer/releases/download/v0.2.5/dsh-plugin-trim-0.2.5.tgz"
16
+ dsh plugin --profile web add "https://github.com/Starlit-Sky-code/dsh-experience-optimizer/releases/download/v0.2.6/dsh-plugin-trim-0.2.6.tgz"
17
17
  ```
18
18
 
19
19
  本地开发:
@@ -40,13 +40,15 @@ dsh plugin --profile web add /absolute/path/to/packages/plugin-trim
40
40
  | `trim_scan_plugins` | 只读 | 插件清单、真实 prompt 上下文成本、使用统计、去重组、兼容性摘要 |
41
41
  | `trim_analyze_compatibility` | 只读 | 兼容性矩阵:插件↔插件、插件↔DSH/Node/平台、Profile/工作区漂移 |
42
42
  | `trim_suggest_profile` | 只写本地草稿 | 按当前任务生成 keep/enable/disable/review 建议与证据 |
43
- | `trim_apply_profile` | 修改 profile | 用户显式确认后应用低风险项,返回回滚 token |
44
- | `trim_rollback_profile` | 修改 profile | 恢复上一次应用 |
43
+ | `trim_apply_profile` | 修改 profile | 提案 + 宿主审批 `allowed-once` 后应用低风险项 |
44
+ | `trim_rollback_profile` | 修改 profile | 宿主审批后恢复上一次应用 |
45
45
 
46
46
  ## 安全边界
47
47
 
48
48
  - 默认只建议,不自动禁用。
49
- - `trim_apply_profile` 必须 `confirm: true`,只应用 `risk: low` 的 disable/enable 项。
49
+ - `trim_apply_profile` 必须 `confirm: true`,但默认还要宿主审批返回 `allowed-once` 才真正写入;`confirm` 只是提案标记。
50
+ - `trim_rollback_profile` 始终需要宿主审批。
51
+ - 只应用 `risk: low`、非受保护的 disable/enable 项。
50
52
  - 受保护项永不改:核心、管理、agent preset、当前 profile 依赖、用户 `protect`/`pinned`、套件自身。
51
53
  - 版本豁免、插件升级、patch 编辑只报告,不自动执行。
52
54
  - 兼容性扫描不执行 `!!js`、不 import 未加载插件、不联网。
@@ -60,6 +62,8 @@ dsh plugin --profile web add /absolute/path/to/packages/plugin-trim
60
62
  - id: dsh-plugin-trim
61
63
  config:
62
64
  mode: advise
65
+ approvalMode: always
66
+ approvalThreshold: 5
63
67
  protect:
64
68
  - my-important-plugin
65
69
  pinned:
@@ -70,7 +74,9 @@ dsh plugin --profile web add /absolute/path/to/packages/plugin-trim
70
74
 
71
75
  | key | 默认 | 说明 |
72
76
  |---|---|---|
73
- | `mode` | `advise` | `auto-safe` 只收窄建议范围,不绕过 confirm |
77
+ | `mode` | `advise` | `auto-safe` 只收窄建议范围 |
78
+ | `approvalMode` | `always` | `always`:每次工具应用都请求宿主审批;`risk-based`:仅超过阈值时审批 |
79
+ | `approvalThreshold` | `5` | `risk-based` 模式下,超过该数量的草稿需要宿主审批 |
74
80
  | `protect` | `[]` | 额外保护包名/entry id |
75
81
  | `pinned` | `[]` | 永不建议禁用 |
76
82
  | `trackUsage` | `true` | 记录工具名/成败/时间,不记录参数 |
package/client.js CHANGED
@@ -1276,7 +1276,7 @@ window.__ModuleLoader__.load({
1276
1276
  { className: 'eo-summary' },
1277
1277
  h(Badge, { tone: 'info' }, 'template: ' + blueprint.template),
1278
1278
  h(Badge, { tone: 'neutral' }, 'permissions: ' + blueprint.permissions.length),
1279
- h(Badge, { tone: 'neutral' }, 'confirm: ' + blueprint.steps.filter((step) => step.needsConfirm).length),
1279
+ h(Badge, { tone: 'warn' }, 'approval required: ' + blueprint.steps.filter((step) => step.approvalLevel === 'required' || step.needsConfirm).length),
1280
1280
  h(Badge, { tone: 'neutral' }, 'min plugins: ' + blueprint.minPluginSet.length),
1281
1281
  ),
1282
1282
  h(
@@ -1293,7 +1293,7 @@ window.__ModuleLoader__.load({
1293
1293
  h('th', null, '类型'),
1294
1294
  h('th', null, '能力'),
1295
1295
  h('th', null, '工具'),
1296
- h('th', null, '确认'),
1296
+ h('th', null, '审批'),
1297
1297
  ),
1298
1298
  ),
1299
1299
  h(
@@ -1313,8 +1313,15 @@ window.__ModuleLoader__.load({
1313
1313
  null,
1314
1314
  h(
1315
1315
  Badge,
1316
- { tone: step.needsConfirm ? 'warn' : 'neutral' },
1317
- step.needsConfirm ? 'yes' : 'no',
1316
+ {
1317
+ tone:
1318
+ (step.approvalLevel ?? (step.needsConfirm ? 'required' : 'none')) === 'required'
1319
+ ? 'danger'
1320
+ : (step.approvalLevel ?? 'none') === 'suggested'
1321
+ ? 'warn'
1322
+ : 'neutral',
1323
+ },
1324
+ step.approvalLevel ?? (step.needsConfirm ? 'required' : 'none'),
1318
1325
  ),
1319
1326
  ),
1320
1327
  ),
package/dist/index.d.ts CHANGED
@@ -4,6 +4,10 @@ import { Context } from "@deepseek-ai/cordis";
4
4
  export interface Config {
5
5
  /** `advise` keeps every suggestion advisory; `auto-safe` only narrows the suggestion set. */
6
6
  mode: 'advise' | 'auto-safe';
7
+ /** `always` asks the host approval service before every tool apply; `risk-based` auto-applies small low-risk drafts. */
8
+ approvalMode: 'always' | 'risk-based';
9
+ /** In `risk-based` mode, drafts larger than this many items require host approval. */
10
+ approvalThreshold: number;
7
11
  /** Extra package names or entry ids that must never be suggested for disable. */
8
12
  protect: string[];
9
13
  /** Packages the user explicitly pinned; never suggested for disable. */
@@ -601,6 +605,8 @@ export declare function buildSlimProfile(scan: ScanResult, task: TaskProfile, co
601
605
  interface ApplyOptions {
602
606
  confirm: boolean;
603
607
  items?: string[];
608
+ /** Pre-generated snapshot token, so an approval reason and the written snapshot share one id. */
609
+ snapshotToken?: string;
604
610
  manager: PluginManagerLike;
605
611
  maxDrafts: number;
606
612
  findings?: readonly CompatFinding[];
package/dist/index.js CHANGED
@@ -13,6 +13,8 @@ import { scopeOf } from "@deepseek-ai/dsh-scope";
13
13
  /** Defaults used when the loader starts the plugin without an explicit config. */
14
14
  const DEFAULT_CONFIG = {
15
15
  mode: "advise",
16
+ approvalMode: "always",
17
+ approvalThreshold: 5,
16
18
  protect: [],
17
19
  pinned: [],
18
20
  trackUsage: true,
@@ -42,6 +44,8 @@ function normalizeConfig(config) {
42
44
  /** Schemastery configuration for the trim plugin. */
43
45
  const Config = z.object({
44
46
  mode: z.union(["advise", "auto-safe"]).default("advise"),
47
+ approvalMode: z.union(["always", "risk-based"]).default("always"),
48
+ approvalThreshold: z.natural().min(1).max(100).default(5),
45
49
  protect: z.array(z.string()).default([]),
46
50
  pinned: z.array(z.string()).default([]),
47
51
  trackUsage: z.boolean().default(true),
@@ -3639,7 +3643,7 @@ async function applySlimProfile(profileId, options) {
3639
3643
  const freshFindings = findingsBySubject(options.findings ?? []);
3640
3644
  const disabledBundles = new Set(candidates.filter((item) => item.kind === "bundle" && item.action === "suggest-disable").map((item) => item.bundleName).filter((name) => name !== void 0));
3641
3645
  candidates = candidates.filter((item) => !(item.kind === "entry" && item.bundleName !== void 0 && disabledBundles.has(item.bundleName)));
3642
- const token = randomToken();
3646
+ const token = options.snapshotToken ?? randomToken();
3643
3647
  const snapshot = {
3644
3648
  schemaVersion: 1,
3645
3649
  token,
@@ -4081,7 +4085,7 @@ function registerSuggestTool(ctx, deps) {
4081
4085
  function registerApplyTool(ctx, deps) {
4082
4086
  ctx.tools.register(defineTool({
4083
4087
  name: "trim_apply_profile",
4084
- description: "Apply low-risk keep/enable/disable items from a saved slim-profile draft. Requires confirm: true and must be called only after the user explicitly approved the exact profileId and items in this conversation. Protected/core/preset items are never changed. Returns a rollback token. Only low-risk disables/enables are applied; compatibility errors can block an item.",
4088
+ description: "Apply low-risk keep/enable/disable items from a saved slim-profile draft. Requires confirm: true, and by default the host approval service must return allowed-once before anything changes. Protected/core/preset items are never changed. Returns a rollback token. Only low-risk disables/enables are applied; compatibility errors can block an item.",
4085
4089
  parameters: {
4086
4090
  profileId: {
4087
4091
  type: "string",
@@ -4091,7 +4095,7 @@ function registerApplyTool(ctx, deps) {
4091
4095
  confirm: {
4092
4096
  type: "boolean",
4093
4097
  required: true,
4094
- description: "Must be true only after explicit user approval of the exact draft."
4098
+ description: "A proposal marker: true means the model has prepared this exact draft and is requesting host approval. The host approval result, not this boolean, is the authorization gate."
4095
4099
  },
4096
4100
  items: {
4097
4101
  type: "array",
@@ -4110,6 +4114,41 @@ function registerApplyTool(ctx, deps) {
4110
4114
  if (args.confirm !== true) return "❌ 应用精简方案需要用户明确确认:请先让用户批准具体的 profileId 与 items,再调用 `trim_apply_profile({ profileId, confirm: true })`。";
4111
4115
  const manager = getPluginManager(ctx);
4112
4116
  if (manager === void 0) return "❌ 当前 profile 没有可用的 pluginManager,无法应用精简方案。请改用 `trim_scan_plugins` 只读查看。";
4117
+ const draft = await loadDraft(args.profileId);
4118
+ if (draft === void 0) return `❌ 未找到精简草稿:${args.profileId}。请先调用 \`trim_suggest_profile\`。`;
4119
+ const wanted = args.items === void 0 ? void 0 : new Set(args.items);
4120
+ const candidates = applicableItems(draft).filter((item) => wanted === void 0 || wanted.has(item.id));
4121
+ const profileName = resolveProfileFacts(ctx, exec.agent).name;
4122
+ const needsApproval = candidates.length > 0 && (deps.config.approvalMode === "always" || candidates.length > deps.config.approvalThreshold);
4123
+ const snapshotToken = needsApproval ? randomToken() : void 0;
4124
+ let approvalNote = "";
4125
+ if (needsApproval) {
4126
+ if (exec.agent === void 0) return "❌ 本次变更需要宿主审批,但当前调用没有 agent,无法发起审批;未应用任何变更。";
4127
+ const approval = ctx.get("approval");
4128
+ if (approval === void 0 || typeof approval.request !== "function") return "❌ 本次变更需要宿主审批,但当前会话没有 approval 服务;未应用任何变更。";
4129
+ let outcome;
4130
+ try {
4131
+ outcome = await approval.request({
4132
+ agent: exec.agent,
4133
+ toolName: "trim_apply_profile",
4134
+ callId: exec.callId,
4135
+ signal: exec.signal,
4136
+ reason: buildApprovalReason(draft, profileName, candidates, snapshotToken ?? "—"),
4137
+ displayReason: {
4138
+ en: `Apply ${candidates.length} low-risk plugin change${candidates.length === 1 ? "" : "s"} to profile "${profileName}"?`,
4139
+ zh: `是否对 profile「${profileName}」应用 ${candidates.length} 项低风险插件变更?`
4140
+ }
4141
+ });
4142
+ } catch (error) {
4143
+ return `❌ 宿主审批调用失败(fail-closed):${error instanceof Error ? error.message : String(error)};未应用任何变更。`;
4144
+ }
4145
+ if (outcome !== "allowed-once") {
4146
+ await audit("apply_profile", "skipped", `approval ${outcome}; draft ${draft.id} kept`);
4147
+ return `❌ 宿主审批未通过(${outcome});未应用任何变更。草稿 \`${draft.id}\` 仍保留,可稍后重新发起。`;
4148
+ }
4149
+ approvalNote = "✅ 宿主审批已通过(allowed-once)。\n\n";
4150
+ await audit("apply_profile", "ok", `approval allowed-once for ${candidates.length} items`);
4151
+ }
4113
4152
  const compat = await analyzeCompatibility(ctx, deps.config, {
4114
4153
  scope: "current",
4115
4154
  includeInfo: true,
@@ -4120,15 +4159,16 @@ function registerApplyTool(ctx, deps) {
4120
4159
  });
4121
4160
  try {
4122
4161
  const result = await applySlimProfile(args.profileId, {
4123
- confirm: args.confirm,
4124
- items: args.items,
4162
+ confirm: true,
4163
+ items: needsApproval ? candidates.map((item) => item.id) : args.items,
4164
+ snapshotToken,
4125
4165
  manager,
4126
4166
  maxDrafts: deps.config.maxDrafts,
4127
4167
  findings: compat.findings,
4128
- profileName: resolveProfileFacts(ctx, exec.agent).name
4168
+ profileName
4129
4169
  });
4130
4170
  await audit("apply_profile", "ok", `applied ${result.items.length} items`);
4131
- return renderApply(result);
4171
+ return approvalNote + renderApply(result);
4132
4172
  } catch (error) {
4133
4173
  if (error instanceof ApplyRefusedError) return `❌ ${error.message}`;
4134
4174
  return `❌ 应用失败:${error instanceof Error ? error.message : String(error)}`;
@@ -4144,7 +4184,7 @@ function registerApplyTool(ctx, deps) {
4144
4184
  function registerRollbackTool(ctx, deps) {
4145
4185
  ctx.tools.register(defineTool({
4146
4186
  name: "trim_rollback_profile",
4147
- description: "Restore plugin enablement from a previous trim apply snapshot. Omit token to use the latest snapshot. Skips items already restored or changed outside trim. Returns per-item results.",
4187
+ description: "Restore plugin enablement from a previous trim apply snapshot. Requires host approval (allowed-once). Omit token to use the latest snapshot. Skips items already restored or changed outside trim. Returns per-item results.",
4148
4188
  parameters: { token: {
4149
4189
  type: "string",
4150
4190
  description: "Rollback token returned by trim_apply_profile. Omit for the latest snapshot."
@@ -4156,18 +4196,46 @@ function registerRollbackTool(ctx, deps) {
4156
4196
  text: value
4157
4197
  }]
4158
4198
  },
4159
- async execute(args) {
4199
+ async execute(args, exec) {
4160
4200
  const manager = getPluginManager(ctx);
4161
4201
  if (manager === void 0) return "❌ 当前 profile 没有可用的 pluginManager,无法回滚。";
4202
+ if (exec.agent === void 0) return "❌ 回滚会修改插件状态,需要宿主审批;当前调用没有 agent,未执行。";
4203
+ const approval = ctx.get("approval");
4204
+ if (approval === void 0 || typeof approval.request !== "function") return "❌ 回滚会修改插件状态,需要宿主审批;当前会话没有 approval 服务,未执行。";
4205
+ const profileName = resolveProfileFacts(ctx, exec.agent).name;
4206
+ let outcome;
4207
+ try {
4208
+ outcome = await approval.request({
4209
+ agent: exec.agent,
4210
+ toolName: "trim_rollback_profile",
4211
+ callId: exec.callId,
4212
+ signal: exec.signal,
4213
+ reason: [
4214
+ `Restore plugin enablement on profile "${profileName}".`,
4215
+ args.token === void 0 ? "Snapshot: latest available rollback snapshot." : `Snapshot: ${args.token}`,
4216
+ "This changes plugin state; the rollback itself is not automatically reversible."
4217
+ ].join("\n"),
4218
+ displayReason: {
4219
+ en: `Restore the plugin state on profile "${profileName}" from ${args.token === void 0 ? "the latest trim snapshot" : "trim snapshot " + args.token}?`,
4220
+ zh: `是否从${args.token === void 0 ? "最近的 trim 快照" : ` trim 快照 ${args.token}`}恢复 profile「${profileName}」的插件状态?`
4221
+ }
4222
+ });
4223
+ } catch (error) {
4224
+ return `❌ 宿主审批调用失败(fail-closed):${error instanceof Error ? error.message : String(error)};未回滚。`;
4225
+ }
4226
+ if (outcome !== "allowed-once") {
4227
+ await audit("rollback_profile", "skipped", `approval ${outcome}`);
4228
+ return `❌ 宿主审批未通过(${outcome});未回滚任何变更。`;
4229
+ }
4162
4230
  try {
4163
4231
  const result = await rollbackSlimProfile({
4164
4232
  token: args.token,
4165
4233
  manager,
4166
4234
  maxDrafts: deps.config.maxDrafts,
4167
- profileName: resolveProfileFacts(ctx).name
4235
+ profileName
4168
4236
  });
4169
4237
  await audit("rollback_profile", "ok", `restored ${result.items.filter((item) => item.status === "restored").length} items`);
4170
- return renderRollback(result);
4238
+ return "✅ 宿主审批已通过(allowed-once)。\n\n" + renderRollback(result);
4171
4239
  } catch (error) {
4172
4240
  return `❌ 回滚失败:${error instanceof Error ? error.message : String(error)}`;
4173
4241
  }
@@ -4179,6 +4247,17 @@ function registerRollbackTool(ctx, deps) {
4179
4247
  })
4180
4248
  }));
4181
4249
  }
4250
+ function buildApprovalReason(draft, profileName, candidates, snapshotToken) {
4251
+ const lines = [
4252
+ `Apply slim profile ${draft.id} (task=${draft.task.tag}) to profile "${profileName}".`,
4253
+ `Snapshot id: ${snapshotToken}`,
4254
+ `Items (${candidates.length}):`,
4255
+ ...candidates.slice(0, 20).map((item) => `- ${item.id} [${item.action}] ${item.name} risk=${item.risk}: ${item.reason}`)
4256
+ ];
4257
+ if (candidates.length > 20) lines.push(`- … ${candidates.length - 20} more`);
4258
+ lines.push("Only low-risk, non-protected items are eligible; a rollback snapshot is written before any change.");
4259
+ return lines.join("\n");
4260
+ }
4182
4261
  async function inventoryOf$1(ctx) {
4183
4262
  const adapter = getInventory(ctx);
4184
4263
  if (adapter === void 0) return void 0;
@@ -4327,7 +4406,7 @@ function renderSuggest(profile, scan, saved = true) {
4327
4406
  lines.push("");
4328
4407
  lines.push(`profileId: \`${profile.id}\``);
4329
4408
  lines.push("");
4330
- lines.push("> 未修改任何插件状态。仅在用户明确同意上述 profileId 与具体 items 后,才调用 `trim_apply_profile({ profileId, confirm: true })`。");
4409
+ lines.push("> 未修改任何插件状态。应用前需要用户确认具体 profileId 与 items,并由宿主审批服务返回 `allowed-once`;`confirm: true` 只是提案标记。");
4331
4410
  lines.push("");
4332
4411
  lines.push(jsonBlock({
4333
4412
  profileId: profile.id,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-trim",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "DSH plugin ecosystem diet and compatibility analyzer",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",