@fish-under-sea/dsh-approval-guide 0.2.1 → 0.2.2

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.en.md ADDED
@@ -0,0 +1,154 @@
1
+ <div align="center">
2
+
3
+ # @fish-under-sea/dsh-approval-guide
4
+
5
+ **Adds a Chinese explanation to every DSH approval prompt: what it will do, what the risks are, and on what basis.**
6
+
7
+ [![npm](https://img.shields.io/npm/v/@fish-under-sea/dsh-approval-guide?style=flat-square&label=npm&color=cb3837)](https://www.npmjs.com/package/@fish-under-sea/dsh-approval-guide)
8
+ ![license](https://img.shields.io/badge/license-MIT-green?style=flat-square)
9
+ ![node](https://img.shields.io/badge/node-%5E22.19.0%20%7C%7C%20%3E%3D24.0.0-339933?style=flat-square)
10
+ ![DSH](https://img.shields.io/badge/DSH-%3E%3D0.2.0--rc.2-4b6ef6?style=flat-square)
11
+ ![plugin](https://img.shields.io/badge/plugin-client%20%2B%20host-6b7280?style=flat-square)
12
+
13
+ [简体中文](README.md) · **English**
14
+
15
+ </div>
16
+
17
+ ## What Problem Does This Solve
18
+
19
+ The approval dialog already ships some Chinese UI strings ("等待审批", "拒绝", "允许一次"), but **the approval reason generated by the host is English-only**. The most common one looks like this:
20
+
21
+ ```text
22
+ escalate sandbox to danger-full-access: <one-line English reason from the model>
23
+ ```
24
+
25
+ The reader has to judge on their own what the command will actually do, how much it will unlock, and what the consequences are — and the English-only template raises that cost. This plugin injects a tiered Chinese explanation below the reason and the command, covering "what it will do / what the risks are / on what basis".
26
+
27
+ ## Result
28
+
29
+ The detail area inside the approval card becomes:
30
+
31
+ ```text
32
+ <original command>
33
+
34
+ What this approval will do
35
+ Escalate the file sandbox scope of this pwsh call to "fully open" (danger-full-access).
36
+ Effective only for this single call: no long-lived grant, no effect on later commands.
37
+ Risk
38
+ Once opened, this command is no longer confined by the workspace boundary: it can read
39
+ and write any file on the host, including system directories, other projects, SSH keys,
40
+ and credential files, and this execution no longer asks for your approval item by item.
41
+ Only allow it if you fully trust this command.
42
+ · Tool: pwsh
43
+ · Target permission: fully open (danger-full-access)
44
+ · Reason given by the model: <original text>
45
+ When in doubt, click "Reject" first: rejecting does not interrupt the conversation;
46
+ I can retry later with read-only or workspace-write instead.
47
+ ```
48
+
49
+ The explanation is always shown in Chinese and does not follow the UI language — switching the interface to English still leaves the Chinese prompt in place.
50
+
51
+ ### Tiered Copy
52
+
53
+ The Chinese explanation is produced by **static rules**: no extra model call, no API quota consumed, and it cannot be swayed by the requester's own wording.
54
+
55
+ | Target permission | Level | Key points of the risk copy |
56
+ | --- | --- | --- |
57
+ | `danger-full-access` | High (red title) | No longer confined by the workspace boundary; can read and write any file on the host (including system directories, other projects, SSH keys, and credential files); this execution no longer asks for approval item by item. |
58
+ | `workspace-write` | Caution | Can write to the current workspace directory and its subdirectories, plus the system temp directory; still cannot write outside the workspace. |
59
+ | Other modes | Caution | Not a built-in DSH mode — no precise scope can be given; prompts that the command will run at the requested permission. |
60
+ | No sandbox parameter | Caution | Generic fallback: the tool requests a higher permission for this single operation, effective only this time. |
61
+
62
+ ## Installation
63
+
64
+ ```sh
65
+ # Install from npm (recommended)
66
+ dsh plugin --profile <profile> add @fish-under-sea/dsh-approval-guide
67
+ ```
68
+
69
+ `--profile` should be followed by the actual profile name on your machine: `desktop` for the desktop app, `web` for the web app.
70
+
71
+ Use `link:` to point at this directory only when you need to modify the source (the repo source is the install source — restart DSH after changes for them to take effect):
72
+
73
+ ```sh
74
+ dsh plugin --profile <profile> add "link:<absolute path to this directory>"
75
+ ```
76
+
77
+ After installation, you need to **restart the DSH app and refresh the page** for it to take effect (the web build has no in-place restart).
78
+
79
+ ### Uninstallation
80
+
81
+ ```sh
82
+ dsh plugin --profile <profile> remove @fish-under-sea/dsh-approval-guide
83
+ ```
84
+
85
+ ### Post-Install Self-Check
86
+
87
+ ```sh
88
+ dsh --profile <profile> --dump-config
89
+ ```
90
+
91
+ The end of the output should contain exactly one `- id: approval-guide` / `name: @fish-under-sea/dsh-approval-guide` entry. Multiple entries mean the plugin is mounted more than once, and the app will fail to start.
92
+
93
+ ## Usage
94
+
95
+ No configuration is needed after installation — the plugin automatically occupies the `conversation.approval.detail` slot of the approval detail area and appends the Chinese explanation to every approval prompt.
96
+
97
+ The explanation is resolved in a defense-in-depth order: first read the tool-call arguments `sandbox_permissions` / `justification`; if those are unavailable, parse the host reason template (`escalate sandbox to <mode>: <reason>`); if that also fails, fall back to the generic explanation. Even when every layer fails to produce a value, a generic Chinese explanation is still shown.
98
+
99
+ Coverage:
100
+
101
+ - All interactive approvals **with a correlated tool call**: sandbox permission escalation, asks triggered by hooks, and asks initiated by other plugins through the approval channel.
102
+
103
+ ## Configuration
104
+
105
+ **No configuration file.** This package has no configuration options and does not read or write any settings file — all rules are hardcoded in `lib/client.js`.
106
+
107
+ ## Compatibility and Boundaries
108
+
109
+ - Platform: pure browser plugin (`dsh.client.platform: web`); the host half is an empty implementation.
110
+ - Occupies the `conversation.approval.detail` sub-slot of the core package `@deepseek-ai/dsh-client-ui-approval`. The slot is of `single` type, sorted by priority in **ascending order** with the **smallest number rendered**; the official occupier `ApprovalCommand` uses the default priority 0, and this plugin registers with `priority: -1` to override it, while re-rendering the original command inside the component using the same logic (`useChat` to fetch the correlated tool call, parsing `argsRaw.command`) so no information is lost.
111
+ - When the component throws, the slot renderer reclaims the entry (abdicate), and the official `ApprovalCommand` automatically resumes rendering — the approval card never goes blank, and the approval flow is never blocked.
112
+ - Compatible with both generations of selectors: DSH 0.2.0 (`useSessionStatus`) and 0.1.x (`useSessionPendingInteraction`).
113
+
114
+ Data sources:
115
+
116
+ | Data | Source |
117
+ | --- | --- |
118
+ | Command and arguments of the correlated tool call | `useChat` selector (same as the official `ApprovalCommand`) |
119
+ | Tool name and approval reason | `useSessionPendingInteraction` / `useSessionStatus` selector (pending interaction with `kind === 'approval'`) |
120
+
121
+ ### Known Limitations
122
+
123
+ - If an approval request has **no correlated tool call** (missing `callId`), the core does not render the detail area, and this plugin has nowhere to insert. This is dictated by the core slot contract and cannot be worked around by this plugin.
124
+ - The Chinese explanation describes the risk at the "permission scope" layer; it does not judge whether the command itself is safe. You still need to read the command yourself.
125
+ - If the host changes the reason template (`escalate sandbox to <mode>: <reason>`), the first-layer argument lookup still works; only the second-layer fallback would stop working.
126
+
127
+ ## Development and Testing
128
+
129
+ ```sh
130
+ node packages/dsh-approval-guide/test/guide.test.mjs
131
+ ```
132
+
133
+ All 12 cases currently pass. The test loads the actual `lib/client.js` that goes into the browser: it uses `node:vm` to provide `window.__ModuleLoader__`, captures the factory registered by the bundle, instantiates it with a fake module table, and directly asserts on the element tree produced by the pure functions and the component. **Zero dependencies** — no need to install React or vitest.
134
+
135
+ > Do not use `node --test test/`: the test runner spawns child processes and captures their piped output, which fails with `EPERM` inside a restricted sandbox. Just run the test file directly.
136
+
137
+ Cases covered: tiered copy for the two sandbox modes, reason-template fallback parsing, unknown modes, generic approval fallback, corrupted argument JSON, no exception on empty input, component preserves the original command, degradation when pending interaction is unavailable, slot registration priority.
138
+
139
+ Directory layout:
140
+
141
+ | Path | Purpose |
142
+ | --- | --- |
143
+ | `lib/index.js` | Host half, empty implementation (pure browser plugin) |
144
+ | `lib/client.js` | Browser half: Chinese copy, tiering logic, approval detail component, slot registration |
145
+ | `cordis.patch.yml` | Bundle patch layer that inserts the plugin entry into the profile registry |
146
+ | `test/guide.test.mjs` | Zero-dependency tests |
147
+
148
+ ## Relationship with the Aggregation Package
149
+
150
+ > This package is one of the members of the [`@fish-under-sea/dsh-fish`](https://github.com/Fish-under-sea/dsh-fish) aggregation package; installing it alone affects only this single item.
151
+
152
+ ## License
153
+
154
+ MIT © Fish-under-sea
package/README.md CHANGED
@@ -6,9 +6,11 @@
6
6
 
7
7
  [![npm](https://img.shields.io/npm/v/@fish-under-sea/dsh-approval-guide?style=flat-square&label=npm&color=cb3837)](https://www.npmjs.com/package/@fish-under-sea/dsh-approval-guide)
8
8
  ![license](https://img.shields.io/badge/license-MIT-green?style=flat-square)
9
- ![node](https://img.shields.io/badge/node-%5E22.19%20%7C%7C%20%3E%3D24-339933?style=flat-square)
9
+ ![node](https://img.shields.io/badge/node-%5E22.19.0%20%7C%7C%20%3E%3D24.0.0-339933?style=flat-square)
10
10
  ![DSH](https://img.shields.io/badge/DSH-%3E%3D0.2.0--rc.2-4b6ef6?style=flat-square)
11
- ![client+host](https://img.shields.io/badge/plugin-client%20%2B%20host-6b7280?style=flat-square)
11
+ ![plugin](https://img.shields.io/badge/plugin-client%20%2B%20host-6b7280?style=flat-square)
12
+
13
+ **简体中文** · [English](README.en.md)
12
14
 
13
15
  </div>
14
16
 
package/cordis.patch.yml CHANGED
@@ -1,12 +1,12 @@
1
- # dsh-approval-guide bundle layer —— 把插件行插入 web profile 的 roster。
2
- #
3
- # 唯一的一行:宿主半区是空实现(纯浏览器插件),浏览器半区占用
4
- # conversation.approval.detail 插槽渲染中文说明。
5
- #
6
- # 安装(在任意目录执行,profile 名按需替换):
7
- # dsh plugin --profile web add link:<本目录>
8
- #
9
- # 本插件没有任何配置项,也不读写设置文件。
10
- - insert:
11
- - id: approval-guide
1
+ # dsh-approval-guide bundle layer —— 把插件行插入 web profile 的 roster。
2
+ #
3
+ # 唯一的一行:宿主半区是空实现(纯浏览器插件),浏览器半区占用
4
+ # conversation.approval.detail 插槽渲染中文说明。
5
+ #
6
+ # 安装(在任意目录执行,profile 名按需替换):
7
+ # dsh plugin --profile web add link:<本目录>
8
+ #
9
+ # 本插件没有任何配置项,也不读写设置文件。
10
+ - insert:
11
+ - id: approval-guide
12
12
  name: '@fish-under-sea/dsh-approval-guide'
package/lib/client.js CHANGED
@@ -1,273 +1,273 @@
1
- // 注册名必须严格等于 package.json 的 name:loader 按行里解析出的包名去
2
- // factories 里认领 factory(@deepseek-ai/dsh-client-modules 的
3
- // "loaded without registering" 校验),对不上就在浏览器侧加载失败。
4
- window.__ModuleLoader__.load({
5
- id: "@fish-under-sea/dsh-approval-guide",
6
- factory: (require) => {
7
- var module = { exports: {} };
8
- var exports = module.exports;
9
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
10
- const react_jsx_runtime = require("react/jsx-runtime");
11
- //#region 样式:复用外壳的设计令牌,跟随明暗主题
12
- const css = ".dag_root{display:flex;flex-direction:column;gap:8px}.dag_command{color:var(--dsw-alias-label-tertiary);font-family:var(--ds-font-family-code,ui-monospace,SFMono-Regular,Menlo,monospace);word-break:break-all;font-size:13px;line-height:20px}.dag_card{display:flex;flex-direction:column;gap:4px;padding:10px 12px;border-radius:12px;background:var(--dsw-alias-state-warn-tertiary);font-family:var(--dsw-font-family,inherit);word-break:normal}.dag_title{color:var(--dsw-alias-label-secondary);font-size:12px;font-weight:600;line-height:18px}.dag_what{color:var(--dsw-alias-label-primary);font-size:13px;line-height:20px}.dag_riskTitle{color:var(--dsw-alias-state-warn-primary);font-size:12px;font-weight:600;line-height:18px;margin-top:2px}.dag_cardDanger .dag_riskTitle{color:var(--dsw-alias-state-error-primary)}.dag_risk{color:var(--dsw-alias-label-primary);font-size:13px;line-height:20px}.dag_check{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px;margin-top:2px}.dag_facts{margin:2px 0 0;padding:0;list-style:none;display:flex;flex-direction:column;gap:2px}.dag_fact{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}.dag_factLabel{color:var(--dsw-alias-label-secondary)}.dag_factValue{word-break:break-word}";
13
- const tagId = "dsh-approval-guide/ApprovalGuide.module.css";
14
- if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) {
15
- const tag = document.createElement("style");
16
- tag.dataset.plugin = "dsh-approval-guide";
17
- tag.dataset.pluginCss = tagId;
18
- tag.textContent = css;
19
- document.head.appendChild(tag);
20
- }
21
- const styles = {
22
- root: "dag_root",
23
- command: "dag_command",
24
- card: "dag_card",
25
- cardDanger: "dag_cardDanger",
26
- title: "dag_title",
27
- what: "dag_what",
28
- riskTitle: "dag_riskTitle",
29
- risk: "dag_risk",
30
- check: "dag_check",
31
- facts: "dag_facts",
32
- fact: "dag_fact",
33
- factLabel: "dag_factLabel",
34
- factValue: "dag_factValue"
35
- };
36
- //#endregion
37
- //#region 中文文案:按沙箱目标模式分级,一律中文显示
38
- /** DSH 内置沙箱模式的中文名。 */
39
- const MODE_LABELS = {
40
- "read-only": "只读(read-only)",
41
- "workspace-write": "工作区可写(workspace-write)",
42
- "danger-full-access": "完全放开(danger-full-access)"
43
- };
44
- /** 危险级别:只有完全放开才标红。 */
45
- const DANGER_MODE = "danger-full-access";
46
- /** 固定的行动建议。 */
47
- const CHECK = "拿不准就先点「拒绝」:拒绝不会中断对话,之后我可以换成只读、或只写工作区内的方式重试。";
48
- /** 找不到工具名时的占位。 */
49
- const UNKNOWN_TOOL = "(未知工具)";
50
- /** 宿主沙箱升级请求的理由句式:`escalate sandbox to <mode>: <理由>`。 */
51
- const SANDBOX_REASON = /^escalate sandbox to\s+([A-Za-z0-9._-]+)\s*:\s*([\s\S]*)$/;
52
- /**
53
- * 解析工具调用的原始参数。
54
- * @param argsRaw - 工具调用参数 JSON 文本。
55
- * @returns 参数对象;缺失或非对象时返回 undefined(绝不抛异常)。
56
- */
57
- function parseCallArgs(argsRaw) {
58
- if (typeof argsRaw !== "string" || argsRaw === "") return void 0;
59
- try {
60
- const parsed = JSON.parse(argsRaw);
61
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
62
- return parsed;
63
- } catch {
64
- return void 0;
65
- }
66
- }
67
- /**
68
- * 从宿主给的英文理由句子里解析沙箱升级信息。
69
- * @param reason - 审批理由原文。
70
- * @returns 目标模式与理由;不匹配时返回 undefined。
71
- */
72
- function parseSandboxReason(reason) {
73
- if (typeof reason !== "string") return void 0;
74
- const matched = SANDBOX_REASON.exec(reason);
75
- if (matched === null) return void 0;
76
- const justification = matched[2].trim();
77
- return {
78
- mode: matched[1],
79
- ...justification === "" ? {} : { justification }
80
- };
81
- }
82
- /** 规整工具名。 */
83
- function toolLabelOf(toolName) {
84
- return typeof toolName === "string" && toolName.trim() !== "" ? toolName.trim() : UNKNOWN_TOOL;
85
- }
86
- /** 沙箱升级的中文说明。 */
87
- function sandboxGuide(toolLabel, mode, justification, known) {
88
- const danger = mode === DANGER_MODE;
89
- const shared = `只对本次调用生效:不产生长期授权,也不影响之后的命令。`;
90
- let what;
91
- let risk;
92
- if (danger) {
93
- what = `把这一次 ${toolLabel} 调用的文件沙箱范围提升到「完全放开」(${mode})。${shared}`;
94
- risk = "放开后这条命令不再受工作区边界约束:它可以读写本机任意文件,包括系统目录、其它项目、SSH 密钥与凭据文件,本次执行也不再逐条征求你的同意。只有在你完全信任这条命令时才应允许。";
95
- } else if (mode === "workspace-write") {
96
- what = `把这一次 ${toolLabel} 调用的文件沙箱范围提升到「工作区可写」(${mode})。${shared}`;
97
- risk = "这条命令可以写入当前工作区目录及其子目录,以及系统临时目录;工作区之外的位置仍然不能写入。请留意命令里是否出现工作区以外的写入路径。";
98
- } else if (known) {
99
- what = `把这一次 ${toolLabel} 调用的权限提升到 ${mode}。${shared}`;
100
- risk = "这条命令会按它请求的权限运行,范围不由工作区边界限定。请先确认命令内容确实是你想执行的操作。";
101
- } else {
102
- what = `把这一次 ${toolLabel} 调用的权限提升到 ${mode}。${shared}`;
103
- risk = "这不是 DSH 内置的沙箱模式,无法给出确切范围。批准后该命令会按它请求的权限运行,可能影响工作区之外的内容。请先确认命令内容可信。";
104
- }
105
- return {
106
- level: danger ? "danger" : "caution",
107
- scope: "sandbox-escalation",
108
- what,
109
- risk
110
- };
111
- }
112
- /** 非沙箱升级的通用中文说明。 */
113
- function genericGuide(toolLabel) {
114
- return {
115
- level: "caution",
116
- scope: "generic",
117
- what: `工具 ${toolLabel} 请求以更高权限执行这一次操作。批准只对本次调用生效,不会形成长期授权。`,
118
- risk: "批准后该工具会按它请求的更高权限运行:可能修改工作区之外的文件、执行系统级命令,或访问本机资源。请先核对上方的理由和下面的命令,确认它确实是你想执行的内容。"
119
- };
120
- }
121
- /**
122
- * 为一次审批生成中文说明(纯函数,不读全局状态,不抛异常)。
123
- * @param input - 工具名、审批理由、关联的工具调用参数。
124
- * @returns 会做什么 / 有什么风险 / 判断依据与建议。
125
- */
126
- function explainApproval(input) {
127
- const source = input === undefined || input === null ? {} : input;
128
- const args = source.args;
129
- const toolLabel = toolLabelOf(source.toolName);
130
- const parsed = parseSandboxReason(source.reason);
131
- const argsMode = typeof args?.sandbox_permissions === "string" && args.sandbox_permissions !== "" ? args.sandbox_permissions : void 0;
132
- const mode = argsMode ?? parsed?.mode;
133
- const argsJustification = typeof args?.justification === "string" && args.justification.trim() !== "" ? args.justification.trim() : void 0;
134
- const justification = argsJustification ?? parsed?.justification;
135
- const command = typeof args?.command === "string" && args.command !== "" ? args.command : void 0;
136
- const body = mode === void 0 ? genericGuide(toolLabel) : sandboxGuide(toolLabel, mode, justification, Object.hasOwn(MODE_LABELS, mode));
137
- const facts = [{ label: "工具", value: toolLabel }];
138
- if (mode !== void 0) facts.push({ label: "目标权限", value: MODE_LABELS[mode] ?? mode });
139
- if (justification !== void 0) facts.push({ label: "模型给的理由", value: justification });
140
- return {
141
- ...body,
142
- check: CHECK,
143
- facts,
144
- ...command === void 0 ? {} : { command },
145
- toolName: source.toolName
146
- };
147
- }
148
- //#endregion
149
- //#region 组件:占用「审批详情」插槽,渲染原命令 + 中文说明
150
- /**
151
- * 在 Chat store 里找与审批关联的工具调用根节点。
152
- * @param snapshot - Chat store 快照。
153
- * @param callId - 审批关联的工具调用 id。
154
- * @returns 工具调用根节点;找不到时返回 undefined。
155
- */
156
- function findCorrelatedCall(snapshot, callId) {
157
- if (snapshot === void 0 || snapshot === null || callId === void 0) return void 0;
158
- const nodes = snapshot.nodes;
159
- if (nodes === void 0 || nodes === null || typeof nodes.values !== "function") return void 0;
160
- for (const node of nodes.values()) {
161
- const root = node?.kind === "tool-call" ? node.data?.root : void 0;
162
- if (root !== void 0 && root !== null && root.callId === callId && !("kind" in root)) return root;
163
- }
164
- return void 0;
165
- }
166
- /**
167
- * 审批卡片内的详情区:原文命令 + 中文风险说明。
168
- * @param props - 插槽标准属性(callId、会话、chat 与待办交互选择器)。
169
- * @returns 详情区元素。
170
- */
171
- function ApprovalGuide(props) {
172
- // 插槽标准属性在 DSH 0.2.0 改名:useSessionPendingInteraction → useSessionStatus,
173
- // 且选择器形状由「会话 Map」变为「会话状态快照」。这里同时兼容两代宿主:
174
- // 0.2.0 走 useSessionStatus(snapshot => snapshot.get(id)?.pendingInteraction),
175
- // 0.1.x 回退 useSessionPendingInteraction(bySession => bySession.get(id))。
176
- const readStatus = props.useSessionStatus;
177
- const readPendingLegacy = props.useSessionPendingInteraction;
178
- const pending = typeof readStatus === "function" ? readStatus((snapshot) => snapshot === void 0 || snapshot === null ? void 0 : snapshot.get(props.sessionId)?.pendingInteraction) : typeof readPendingLegacy === "function" ? readPendingLegacy((bySession) => bySession === void 0 || bySession === null ? void 0 : bySession.get(props.sessionId)) : void 0;
179
- const approval = pending !== void 0 && pending !== null && pending.kind === "approval" ? pending : void 0;
180
- const readChat = props.useChat;
181
- const argsRaw = typeof readChat === "function" ? readChat((snapshot) => {
182
- const call = findCorrelatedCall(snapshot, props.callId);
183
- return call === void 0 || call === null ? void 0 : call.argsRaw;
184
- }) : void 0;
185
- const guide = explainApproval({
186
- toolName: approval === void 0 ? void 0 : approval.toolName,
187
- reason: approval === void 0 ? void 0 : approval.reason,
188
- args: parseCallArgs(argsRaw)
189
- });
190
- const children = [];
191
- if (guide.command !== void 0) children.push((0, react_jsx_runtime.jsx)("div", {
192
- className: styles.command,
193
- children: guide.command
194
- }, "command"));
195
- const card = [
196
- (0, react_jsx_runtime.jsx)("div", {
197
- className: styles.title,
198
- children: "这次审批会做什么"
199
- }, "whatTitle"),
200
- (0, react_jsx_runtime.jsx)("div", {
201
- className: styles.what,
202
- children: guide.what
203
- }, "what"),
204
- (0, react_jsx_runtime.jsx)("div", {
205
- className: styles.riskTitle,
206
- children: "风险"
207
- }, "riskTitle"),
208
- (0, react_jsx_runtime.jsx)("div", {
209
- className: styles.risk,
210
- children: guide.risk
211
- }, "risk")
212
- ];
213
- if (guide.facts.length > 0) card.push((0, react_jsx_runtime.jsx)("ul", {
214
- className: styles.facts,
215
- children: guide.facts.map((fact, index) => (0, react_jsx_runtime.jsx)("li", {
216
- className: styles.fact,
217
- children: [(0, react_jsx_runtime.jsx)("span", {
218
- className: styles.factLabel,
219
- children: `${fact.label}:`
220
- }, "label"), (0, react_jsx_runtime.jsx)("span", {
221
- className: styles.factValue,
222
- children: fact.value
223
- }, "value")]
224
- }, `fact-${String(index)}`))
225
- }, "facts"));
226
- card.push((0, react_jsx_runtime.jsx)("div", {
227
- className: styles.check,
228
- children: guide.check
229
- }, "check"));
230
- children.push((0, react_jsx_runtime.jsx)("div", {
231
- className: guide.level === "danger" ? `${styles.card} ${styles.cardDanger}` : styles.card,
232
- children: card
233
- }, "guide"));
234
- return (0, react_jsx_runtime.jsx)("div", {
235
- className: styles.root,
236
- "data-approval-guide": guide.scope,
237
- children
238
- });
239
- }
240
- //#endregion
241
- //#region 插件挂载
242
- /** 必需服务:插槽注册表。 */
243
- const inject = ["slots"];
244
- /**
245
- * 把中文说明挂到审批详情插槽。
246
- *
247
- * `conversation.approval.detail` 是 single 插槽,官方占用者是
248
- * `@deepseek-ai/dsh-client-ui-chat` 的 ApprovalCommand(默认优先级 0);
249
- * single 插槽同级注册会直接报错,且优先级数字最小者渲染,因此这里用 -1
250
- * 覆盖它,并在组件里自己把原始命令重新渲染回来。组件崩溃时条目会被
251
- * 回收(abdicate),自动退回官方实现,不会留下空白审批卡。
252
- *
253
- * @param ctx - 客户端根上下文。
254
- */
255
- function apply(ctx) {
256
- ctx.slots.inject("conversation.approval.detail", () => ctx.slots.register({
257
- name: "conversation.approval.detail",
258
- priority: -1
259
- }, ApprovalGuide));
260
- }
261
- //#endregion
262
- exports.apply = apply;
263
- exports.inject = inject;
264
- exports.__internals = {
265
- ApprovalGuide,
266
- explainApproval,
267
- parseCallArgs,
268
- parseSandboxReason,
269
- findCorrelatedCall
270
- };
271
- return module.exports;
272
- }
1
+ // 注册名必须严格等于 package.json 的 name:loader 按行里解析出的包名去
2
+ // factories 里认领 factory(@deepseek-ai/dsh-client-modules 的
3
+ // "loaded without registering" 校验),对不上就在浏览器侧加载失败。
4
+ window.__ModuleLoader__.load({
5
+ id: "@fish-under-sea/dsh-approval-guide",
6
+ factory: (require) => {
7
+ var module = { exports: {} };
8
+ var exports = module.exports;
9
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
10
+ const react_jsx_runtime = require("react/jsx-runtime");
11
+ //#region 样式:复用外壳的设计令牌,跟随明暗主题
12
+ const css = ".dag_root{display:flex;flex-direction:column;gap:8px}.dag_command{color:var(--dsw-alias-label-tertiary);font-family:var(--ds-font-family-code,ui-monospace,SFMono-Regular,Menlo,monospace);word-break:break-all;font-size:13px;line-height:20px}.dag_card{display:flex;flex-direction:column;gap:4px;padding:10px 12px;border-radius:12px;background:var(--dsw-alias-state-warn-tertiary);font-family:var(--dsw-font-family,inherit);word-break:normal}.dag_title{color:var(--dsw-alias-label-secondary);font-size:12px;font-weight:600;line-height:18px}.dag_what{color:var(--dsw-alias-label-primary);font-size:13px;line-height:20px}.dag_riskTitle{color:var(--dsw-alias-state-warn-primary);font-size:12px;font-weight:600;line-height:18px;margin-top:2px}.dag_cardDanger .dag_riskTitle{color:var(--dsw-alias-state-error-primary)}.dag_risk{color:var(--dsw-alias-label-primary);font-size:13px;line-height:20px}.dag_check{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px;margin-top:2px}.dag_facts{margin:2px 0 0;padding:0;list-style:none;display:flex;flex-direction:column;gap:2px}.dag_fact{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}.dag_factLabel{color:var(--dsw-alias-label-secondary)}.dag_factValue{word-break:break-word}";
13
+ const tagId = "dsh-approval-guide/ApprovalGuide.module.css";
14
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) {
15
+ const tag = document.createElement("style");
16
+ tag.dataset.plugin = "dsh-approval-guide";
17
+ tag.dataset.pluginCss = tagId;
18
+ tag.textContent = css;
19
+ document.head.appendChild(tag);
20
+ }
21
+ const styles = {
22
+ root: "dag_root",
23
+ command: "dag_command",
24
+ card: "dag_card",
25
+ cardDanger: "dag_cardDanger",
26
+ title: "dag_title",
27
+ what: "dag_what",
28
+ riskTitle: "dag_riskTitle",
29
+ risk: "dag_risk",
30
+ check: "dag_check",
31
+ facts: "dag_facts",
32
+ fact: "dag_fact",
33
+ factLabel: "dag_factLabel",
34
+ factValue: "dag_factValue"
35
+ };
36
+ //#endregion
37
+ //#region 中文文案:按沙箱目标模式分级,一律中文显示
38
+ /** DSH 内置沙箱模式的中文名。 */
39
+ const MODE_LABELS = {
40
+ "read-only": "只读(read-only)",
41
+ "workspace-write": "工作区可写(workspace-write)",
42
+ "danger-full-access": "完全放开(danger-full-access)"
43
+ };
44
+ /** 危险级别:只有完全放开才标红。 */
45
+ const DANGER_MODE = "danger-full-access";
46
+ /** 固定的行动建议。 */
47
+ const CHECK = "拿不准就先点「拒绝」:拒绝不会中断对话,之后我可以换成只读、或只写工作区内的方式重试。";
48
+ /** 找不到工具名时的占位。 */
49
+ const UNKNOWN_TOOL = "(未知工具)";
50
+ /** 宿主沙箱升级请求的理由句式:`escalate sandbox to <mode>: <理由>`。 */
51
+ const SANDBOX_REASON = /^escalate sandbox to\s+([A-Za-z0-9._-]+)\s*:\s*([\s\S]*)$/;
52
+ /**
53
+ * 解析工具调用的原始参数。
54
+ * @param argsRaw - 工具调用参数 JSON 文本。
55
+ * @returns 参数对象;缺失或非对象时返回 undefined(绝不抛异常)。
56
+ */
57
+ function parseCallArgs(argsRaw) {
58
+ if (typeof argsRaw !== "string" || argsRaw === "") return void 0;
59
+ try {
60
+ const parsed = JSON.parse(argsRaw);
61
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
62
+ return parsed;
63
+ } catch {
64
+ return void 0;
65
+ }
66
+ }
67
+ /**
68
+ * 从宿主给的英文理由句子里解析沙箱升级信息。
69
+ * @param reason - 审批理由原文。
70
+ * @returns 目标模式与理由;不匹配时返回 undefined。
71
+ */
72
+ function parseSandboxReason(reason) {
73
+ if (typeof reason !== "string") return void 0;
74
+ const matched = SANDBOX_REASON.exec(reason);
75
+ if (matched === null) return void 0;
76
+ const justification = matched[2].trim();
77
+ return {
78
+ mode: matched[1],
79
+ ...justification === "" ? {} : { justification }
80
+ };
81
+ }
82
+ /** 规整工具名。 */
83
+ function toolLabelOf(toolName) {
84
+ return typeof toolName === "string" && toolName.trim() !== "" ? toolName.trim() : UNKNOWN_TOOL;
85
+ }
86
+ /** 沙箱升级的中文说明。 */
87
+ function sandboxGuide(toolLabel, mode, justification, known) {
88
+ const danger = mode === DANGER_MODE;
89
+ const shared = `只对本次调用生效:不产生长期授权,也不影响之后的命令。`;
90
+ let what;
91
+ let risk;
92
+ if (danger) {
93
+ what = `把这一次 ${toolLabel} 调用的文件沙箱范围提升到「完全放开」(${mode})。${shared}`;
94
+ risk = "放开后这条命令不再受工作区边界约束:它可以读写本机任意文件,包括系统目录、其它项目、SSH 密钥与凭据文件,本次执行也不再逐条征求你的同意。只有在你完全信任这条命令时才应允许。";
95
+ } else if (mode === "workspace-write") {
96
+ what = `把这一次 ${toolLabel} 调用的文件沙箱范围提升到「工作区可写」(${mode})。${shared}`;
97
+ risk = "这条命令可以写入当前工作区目录及其子目录,以及系统临时目录;工作区之外的位置仍然不能写入。请留意命令里是否出现工作区以外的写入路径。";
98
+ } else if (known) {
99
+ what = `把这一次 ${toolLabel} 调用的权限提升到 ${mode}。${shared}`;
100
+ risk = "这条命令会按它请求的权限运行,范围不由工作区边界限定。请先确认命令内容确实是你想执行的操作。";
101
+ } else {
102
+ what = `把这一次 ${toolLabel} 调用的权限提升到 ${mode}。${shared}`;
103
+ risk = "这不是 DSH 内置的沙箱模式,无法给出确切范围。批准后该命令会按它请求的权限运行,可能影响工作区之外的内容。请先确认命令内容可信。";
104
+ }
105
+ return {
106
+ level: danger ? "danger" : "caution",
107
+ scope: "sandbox-escalation",
108
+ what,
109
+ risk
110
+ };
111
+ }
112
+ /** 非沙箱升级的通用中文说明。 */
113
+ function genericGuide(toolLabel) {
114
+ return {
115
+ level: "caution",
116
+ scope: "generic",
117
+ what: `工具 ${toolLabel} 请求以更高权限执行这一次操作。批准只对本次调用生效,不会形成长期授权。`,
118
+ risk: "批准后该工具会按它请求的更高权限运行:可能修改工作区之外的文件、执行系统级命令,或访问本机资源。请先核对上方的理由和下面的命令,确认它确实是你想执行的内容。"
119
+ };
120
+ }
121
+ /**
122
+ * 为一次审批生成中文说明(纯函数,不读全局状态,不抛异常)。
123
+ * @param input - 工具名、审批理由、关联的工具调用参数。
124
+ * @returns 会做什么 / 有什么风险 / 判断依据与建议。
125
+ */
126
+ function explainApproval(input) {
127
+ const source = input === undefined || input === null ? {} : input;
128
+ const args = source.args;
129
+ const toolLabel = toolLabelOf(source.toolName);
130
+ const parsed = parseSandboxReason(source.reason);
131
+ const argsMode = typeof args?.sandbox_permissions === "string" && args.sandbox_permissions !== "" ? args.sandbox_permissions : void 0;
132
+ const mode = argsMode ?? parsed?.mode;
133
+ const argsJustification = typeof args?.justification === "string" && args.justification.trim() !== "" ? args.justification.trim() : void 0;
134
+ const justification = argsJustification ?? parsed?.justification;
135
+ const command = typeof args?.command === "string" && args.command !== "" ? args.command : void 0;
136
+ const body = mode === void 0 ? genericGuide(toolLabel) : sandboxGuide(toolLabel, mode, justification, Object.hasOwn(MODE_LABELS, mode));
137
+ const facts = [{ label: "工具", value: toolLabel }];
138
+ if (mode !== void 0) facts.push({ label: "目标权限", value: MODE_LABELS[mode] ?? mode });
139
+ if (justification !== void 0) facts.push({ label: "模型给的理由", value: justification });
140
+ return {
141
+ ...body,
142
+ check: CHECK,
143
+ facts,
144
+ ...command === void 0 ? {} : { command },
145
+ toolName: source.toolName
146
+ };
147
+ }
148
+ //#endregion
149
+ //#region 组件:占用「审批详情」插槽,渲染原命令 + 中文说明
150
+ /**
151
+ * 在 Chat store 里找与审批关联的工具调用根节点。
152
+ * @param snapshot - Chat store 快照。
153
+ * @param callId - 审批关联的工具调用 id。
154
+ * @returns 工具调用根节点;找不到时返回 undefined。
155
+ */
156
+ function findCorrelatedCall(snapshot, callId) {
157
+ if (snapshot === void 0 || snapshot === null || callId === void 0) return void 0;
158
+ const nodes = snapshot.nodes;
159
+ if (nodes === void 0 || nodes === null || typeof nodes.values !== "function") return void 0;
160
+ for (const node of nodes.values()) {
161
+ const root = node?.kind === "tool-call" ? node.data?.root : void 0;
162
+ if (root !== void 0 && root !== null && root.callId === callId && !("kind" in root)) return root;
163
+ }
164
+ return void 0;
165
+ }
166
+ /**
167
+ * 审批卡片内的详情区:原文命令 + 中文风险说明。
168
+ * @param props - 插槽标准属性(callId、会话、chat 与待办交互选择器)。
169
+ * @returns 详情区元素。
170
+ */
171
+ function ApprovalGuide(props) {
172
+ // 插槽标准属性在 DSH 0.2.0 改名:useSessionPendingInteraction → useSessionStatus,
173
+ // 且选择器形状由「会话 Map」变为「会话状态快照」。这里同时兼容两代宿主:
174
+ // 0.2.0 走 useSessionStatus(snapshot => snapshot.get(id)?.pendingInteraction),
175
+ // 0.1.x 回退 useSessionPendingInteraction(bySession => bySession.get(id))。
176
+ const readStatus = props.useSessionStatus;
177
+ const readPendingLegacy = props.useSessionPendingInteraction;
178
+ const pending = typeof readStatus === "function" ? readStatus((snapshot) => snapshot === void 0 || snapshot === null ? void 0 : snapshot.get(props.sessionId)?.pendingInteraction) : typeof readPendingLegacy === "function" ? readPendingLegacy((bySession) => bySession === void 0 || bySession === null ? void 0 : bySession.get(props.sessionId)) : void 0;
179
+ const approval = pending !== void 0 && pending !== null && pending.kind === "approval" ? pending : void 0;
180
+ const readChat = props.useChat;
181
+ const argsRaw = typeof readChat === "function" ? readChat((snapshot) => {
182
+ const call = findCorrelatedCall(snapshot, props.callId);
183
+ return call === void 0 || call === null ? void 0 : call.argsRaw;
184
+ }) : void 0;
185
+ const guide = explainApproval({
186
+ toolName: approval === void 0 ? void 0 : approval.toolName,
187
+ reason: approval === void 0 ? void 0 : approval.reason,
188
+ args: parseCallArgs(argsRaw)
189
+ });
190
+ const children = [];
191
+ if (guide.command !== void 0) children.push((0, react_jsx_runtime.jsx)("div", {
192
+ className: styles.command,
193
+ children: guide.command
194
+ }, "command"));
195
+ const card = [
196
+ (0, react_jsx_runtime.jsx)("div", {
197
+ className: styles.title,
198
+ children: "这次审批会做什么"
199
+ }, "whatTitle"),
200
+ (0, react_jsx_runtime.jsx)("div", {
201
+ className: styles.what,
202
+ children: guide.what
203
+ }, "what"),
204
+ (0, react_jsx_runtime.jsx)("div", {
205
+ className: styles.riskTitle,
206
+ children: "风险"
207
+ }, "riskTitle"),
208
+ (0, react_jsx_runtime.jsx)("div", {
209
+ className: styles.risk,
210
+ children: guide.risk
211
+ }, "risk")
212
+ ];
213
+ if (guide.facts.length > 0) card.push((0, react_jsx_runtime.jsx)("ul", {
214
+ className: styles.facts,
215
+ children: guide.facts.map((fact, index) => (0, react_jsx_runtime.jsx)("li", {
216
+ className: styles.fact,
217
+ children: [(0, react_jsx_runtime.jsx)("span", {
218
+ className: styles.factLabel,
219
+ children: `${fact.label}:`
220
+ }, "label"), (0, react_jsx_runtime.jsx)("span", {
221
+ className: styles.factValue,
222
+ children: fact.value
223
+ }, "value")]
224
+ }, `fact-${String(index)}`))
225
+ }, "facts"));
226
+ card.push((0, react_jsx_runtime.jsx)("div", {
227
+ className: styles.check,
228
+ children: guide.check
229
+ }, "check"));
230
+ children.push((0, react_jsx_runtime.jsx)("div", {
231
+ className: guide.level === "danger" ? `${styles.card} ${styles.cardDanger}` : styles.card,
232
+ children: card
233
+ }, "guide"));
234
+ return (0, react_jsx_runtime.jsx)("div", {
235
+ className: styles.root,
236
+ "data-approval-guide": guide.scope,
237
+ children
238
+ });
239
+ }
240
+ //#endregion
241
+ //#region 插件挂载
242
+ /** 必需服务:插槽注册表。 */
243
+ const inject = ["slots"];
244
+ /**
245
+ * 把中文说明挂到审批详情插槽。
246
+ *
247
+ * `conversation.approval.detail` 是 single 插槽,官方占用者是
248
+ * `@deepseek-ai/dsh-client-ui-chat` 的 ApprovalCommand(默认优先级 0);
249
+ * single 插槽同级注册会直接报错,且优先级数字最小者渲染,因此这里用 -1
250
+ * 覆盖它,并在组件里自己把原始命令重新渲染回来。组件崩溃时条目会被
251
+ * 回收(abdicate),自动退回官方实现,不会留下空白审批卡。
252
+ *
253
+ * @param ctx - 客户端根上下文。
254
+ */
255
+ function apply(ctx) {
256
+ ctx.slots.inject("conversation.approval.detail", () => ctx.slots.register({
257
+ name: "conversation.approval.detail",
258
+ priority: -1
259
+ }, ApprovalGuide));
260
+ }
261
+ //#endregion
262
+ exports.apply = apply;
263
+ exports.inject = inject;
264
+ exports.__internals = {
265
+ ApprovalGuide,
266
+ explainApproval,
267
+ parseCallArgs,
268
+ parseSandboxReason,
269
+ findCorrelatedCall
270
+ };
271
+ return module.exports;
272
+ }
273
273
  });
package/lib/index.js CHANGED
@@ -1,5 +1,5 @@
1
- //#region src/index.ts
2
- /** 宿主半区:本插件是纯浏览器插件,宿主侧没有任何行为。 */
3
- function apply(_ctx) {}
4
- //#endregion
1
+ //#region src/index.ts
2
+ /** 宿主半区:本插件是纯浏览器插件,宿主侧没有任何行为。 */
3
+ function apply(_ctx) {}
4
+ //#endregion
5
5
  export { apply };
package/package.json CHANGED
@@ -1,55 +1,56 @@
1
- {
2
- "name": "@fish-under-sea/dsh-approval-guide",
3
- "version": "0.2.1",
4
- "description": "在 DSH Web GUI 的审批弹窗里追加中文说明:这次审批会做什么、有什么风险、依据是什么。原英文理由与命令原文保留显示。",
5
- "type": "module",
6
- "main": "./lib/index.js",
7
- "exports": {
8
- ".": {
9
- "default": "./lib/index.js"
10
- },
11
- "./client": {
12
- "default": "./lib/client.js"
13
- },
14
- "./package.json": "./package.json"
15
- },
16
- "files": [
17
- "lib",
18
- "cordis.patch.yml",
19
- "README.md"
20
- ],
21
- "license": "MIT",
22
- "publishConfig": {
23
- "access": "public"
24
- },
25
- "engines": {
26
- "node": "^22.19.0 || >=24.0.0"
27
- },
28
- "keywords": [
29
- "dsh",
30
- "dsh-plugin",
31
- "approval",
32
- "sandbox",
33
- "chinese"
34
- ],
35
- "scripts": {
36
- "test": "node test/guide.test.mjs"
37
- },
38
- "repository": {
39
- "type": "git",
40
- "url": "https://github.com/Fish-under-sea/dsh-fish.git",
41
- "directory": "packages/dsh-approval-guide"
42
- },
43
- "dsh": {
44
- "engines": {
45
- "dsh": ">=0.2.0-rc.2"
46
- },
47
- "bundle": {
48
- "patch": "./cordis.patch.yml"
49
- },
50
- "client": {
51
- "inject": [],
52
- "platform": "web"
53
- }
54
- }
1
+ {
2
+ "name": "@fish-under-sea/dsh-approval-guide",
3
+ "version": "0.2.2",
4
+ "description": "在 DSH Web GUI 的审批弹窗里追加中文说明:这次审批会做什么、有什么风险、依据是什么。原英文理由与命令原文保留显示。",
5
+ "type": "module",
6
+ "main": "./lib/index.js",
7
+ "exports": {
8
+ ".": {
9
+ "default": "./lib/index.js"
10
+ },
11
+ "./client": {
12
+ "default": "./lib/client.js"
13
+ },
14
+ "./package.json": "./package.json"
15
+ },
16
+ "files": [
17
+ "lib",
18
+ "cordis.patch.yml",
19
+ "README.md",
20
+ "README.en.md"
21
+ ],
22
+ "license": "MIT",
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "engines": {
27
+ "node": "^22.19.0 || >=24.0.0"
28
+ },
29
+ "keywords": [
30
+ "dsh",
31
+ "dsh-plugin",
32
+ "approval",
33
+ "sandbox",
34
+ "chinese"
35
+ ],
36
+ "scripts": {
37
+ "test": "node test/guide.test.mjs"
38
+ },
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/Fish-under-sea/dsh-fish.git",
42
+ "directory": "packages/dsh-approval-guide"
43
+ },
44
+ "dsh": {
45
+ "engines": {
46
+ "dsh": ">=0.2.0-rc.2"
47
+ },
48
+ "bundle": {
49
+ "patch": "./cordis.patch.yml"
50
+ },
51
+ "client": {
52
+ "inject": [],
53
+ "platform": "web"
54
+ }
55
+ }
55
56
  }