dsh-web-toggle 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-web-toggle contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,97 @@
1
- # Temporary Holding Version
1
+ # dsh-web-toggle
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 给 DSH 对话输入框工具栏加一个**按会话独立**的断网开关。装上之后,输入框左边多一个小地球:
4
+
5
+ - 亮着:本会话工具齐全(`web_search` / `web_fetch`、shell、浏览器、MCP 都在)。
6
+ - 点灭:本会话**只剩不能出网的工具**——网页搜索、浏览器、MCP、生图/视频、子代理、插件管理、定时任务全部从工具列表里消失,`ops_bash` 保留但加命令过滤。下一次请求生效。
7
+ - 再点一次恢复。**只影响这一个会话**,别的会话和本地功能照旧。
8
+
9
+ 底层用的是 DSH 内核自带的 `agent.ctx.tools.restrict()`:作用域绑定在 agent 上,返回精确的 disposer,所以隔离是天然的、按会话的、可逆的。用的是**白名单**而不是只 deny 两个名字:只 deny `web_search` / `web_fetch` 挡不住 shell、浏览器、MCP 这些通用通道;白名单才能默认关门——将来别的插件新加的工具也一样被挡在外面,直到有人把它加进白名单。
10
+
11
+ ## 安装
12
+
13
+ 需要 DSH `>= 0.2.2-rc.1 < 0.3.0`。
14
+
15
+ 源码目录直接装(推荐,改代码后要同步):
16
+
17
+ ```
18
+ plugin_manager install_bundle target="file:E:/workspace/dsh-web-toggle-prompt-20261116/dsh-web-toggle"
19
+ ```
20
+
21
+ 装完 **刷新页面**(新的客户端模块要重新下发)。Host 半侧随 DSH 启动加载;插件管理器里禁用再启用即可热重载。
22
+
23
+ pnpm 对 `file:` 依赖做的是**拷贝**,不是软链:改完源码要 `node scripts/sync-to-profile.mjs` 把文件同步进 `C:\Users\Aluminium\.dsh\profiles\desktop\node_modules\dsh-web-toggle\`,再热重载。
24
+
25
+ ## 命令
26
+
27
+ | 命令 | 作用 |
28
+ | --- | --- |
29
+ | `/webtoggle` | 切换 |
30
+ | `/webtoggle on` / `off` | 显式开关(幂等) |
31
+ | `/webtoggle status` | 只读状态 |
32
+
33
+ 轮次正在执行时切换会被**拒绝**(不排队):同一轮里前后两个请求的工具声明不一致会让模型困惑。
34
+
35
+ ## 它挡什么
36
+
37
+ **隐藏**:`web_search`、`web_fetch`、浏览器(`bsk_*`)、`computer_*`(能驱动浏览器看网页)、全部 `mcp__*` 与 MCP 资源读取、`video_*`、`workbuddy_*`、`subagent` / `subagent_fork` / `workflow` / `send_message`(子代理是新的 Agent,遮罩跟不过去)、`plugin_manager`(装包=下载)、`schedule_create` / `schedule_edit`(会安排另一个会话去联网)。
38
+
39
+ **留下、但加命令过滤**:`ops_bash`。本地活照跑;命令里出现联网迹象就在执行前拦下。
40
+
41
+ **留下(纯本地,不设防)**:文件读写与检索、上下文/记忆、计划与目标、技能、`job_*` 查看与终止、`schedule_list` / `schedule_view`、`present`、`ask_user_question` 等。
42
+
43
+ 被拦下的调用会收到一条**写成指令的拒绝理由**,而不是只说"被拦了":
44
+
45
+ > 规则:本会话暂时不允许使用一切形式的联网工具。不要换别的工具、不要写脚本或编码后执行、不要起子进程去找替代通道——开关打开之前这里的任何联网尝试都会被拦下。真的需要联网时,停下来向用户说明「需要联网」,请用户暂时打开开关;如果怀疑是误判,也照此处理。
46
+
47
+ ## 命令过滤的三层
48
+
49
+ 1. **字面匹配**:命令行客户端(`curl` / `wget` / `ssh` / `nc` / `ping` …)、联网式仓库与包管理操作(`git clone`、`npm view|pack|install`、`pip install`、`gh release` …)、URL 与 UNC、解释器的网络模块(`import socket` / `require('net')` / `ssl` / `urllib` …)、PowerShell/.NET 的下载器与 `-EncodedCommand`、`base64 -d | sh`。
50
+ 2. **去伪装再匹配**:先去掉 `'` `"` 反引号 `^` `\` `+` 和 `${IFS}`,把 `so''cket`、`"cur""l"`、`__import__('so'+'cket')` 还原成真名后再匹配一遍。
51
+ 3. **看它要执行的文件**:命令带解释器(`python` / `node` / `bash` / `pwsh` / `source` …)和脚本路径时,按 `workdir` → 会话目录 → 进程目录解析,**真的把文件读出来**(≤256 KB,一层递归)用同一套规则看内容;`npm run x` / `pnpm x` 会读 `package.json` 的 `scripts.x`,再查它引用的脚本。
52
+
53
+ 读不到文件**一律放行**:读不到的东西也跑不起来,而对读不到的东西 fail-closed 会让正常工程挂掉。
54
+
55
+ ## 挡不住什么(如实写)
56
+
57
+ 这一层是**提示性护栏,不是网络层的墙**。DSH 内核没有"按会话断网"的能力(`dsh-sandbox-local` 只约束文件系统,没有网络规则),所以:
58
+
59
+ 1. **运行时拼出来的名字**:`chr(115)+chr(111)+...`、`getattr(mod, name)` 之类,文本里没有任何关键词,只有解释器知道会拼出什么。
60
+ 2. **脚本放在三个候选目录之外**(读不到 → 放行),或者改名到没有扩展名。
61
+ 3. **编译器产物**:`gcc` / `rustc` 编译出联网二进制,文本层只看到"编译"。
62
+ 4. **已经在跑的东西**:关之前起的后台任务、计划任务、服务不会自动断;用 `job_list` + `job_kill` 收尾。
63
+ 5. **`run_code` 是内核保留名**,`tools.restrict()` 不接受它,所以 PTC 模式下仍可见;它自身没有网络 API,但它起的子代理是否受限取决于内核。
64
+ 6. 真要"一个字节都不许出",只能在无网 VM/容器里跑 DSH——那不是插件能做的事。
65
+
66
+ ## 性能
67
+
68
+ 几乎为零。Host 半侧只在切换时读一次工具目录(约 100 个名字的过滤),平日只有两个事件监听器;每次 admitted step 只做一次 `Set.has`。断网期间每次 `ops_bash` 多一次正则(以及必要时读一个脚本文件,≤256 KB,不做目录遍历)。客户端是一小组件,只在状态变化时渲染——没有轮询、没有常驻定时器。
69
+
70
+ ## 开发与测试
71
+
72
+ ```bash
73
+ node tests/host.test.mjs # 12 组:开关、幂等、隔离、序列重建、白名单、命令过滤
74
+ node tests/client.test.mjs # 8 组:按钮两态、探针、失败分支、切走切回
75
+ node scripts/sync-to-profile.mjs
76
+ ```
77
+
78
+ `tests/host.test.mjs` 里的命令过滤用例包含三轮红队实测:直白写法、引号/加号拆分、写盘再执行、`npm run` 脚本体,以及一组本地命令的回归基线(`pnpm run build`、`git status`、`python -c "print(1+1)"`、`node scripts/x.mjs` …)。
79
+
80
+ 更多设计细节见 [docs/DETAIL.md](docs/DETAIL.md),红队记录见 [docs/REDTEAM.md](docs/REDTEAM.md),真机验证见 [docs/VERIFY.md](docs/VERIFY.md)。
81
+
82
+ ## 目录
83
+
84
+ ```
85
+ index.js Host 半侧:命令、restrict、guard、请求序列重建
86
+ client.js Browser 半侧:输入框按钮、状态、locale
87
+ cordis.patch.yml 把插件插进 profile 的 bundle 补丁
88
+ locale/{en,zh}.json 插件管理器里的标题/描述/详情路径
89
+ icon.svg 插件图标
90
+ docs/ DETAIL / REDTEAM / VERIFY
91
+ tests/ host 与 client 的离线测试
92
+ scripts/ 同步进 profile 的脚本
93
+ ```
94
+
95
+ ## 许可
96
+
97
+ MIT
package/client.js ADDED
@@ -0,0 +1,381 @@
1
+ /**
2
+ * Browser half of the web-toggle bundle.
3
+ *
4
+ * Renders one toggle in the composer tool row (conversation.input.left) and drives
5
+ * the bundle's Host `/webtoggle` command. The button state is per Session: the
6
+ * browser remembers it under the Session id so a page reload keeps showing the
7
+ * truth, and a mount with a remembered "off" asks the Host once (`/webtoggle
8
+ * status`) because a DSH restart resets the Host side.
9
+ * Remotes used: commands.
10
+ */
11
+ window.__ModuleLoader__.load({
12
+ id: 'dsh-web-toggle',
13
+ factory(require) {
14
+ const React = require('react')
15
+ const h = React.createElement
16
+ const { useEffect, useRef, useState } = React
17
+
18
+ /** Locale namespace of this control. */
19
+ const NS = 'web-toggle'
20
+ /** Marker used to install the stylesheet once and remove it on unload. */
21
+ const STYLE_ID = 'dsh-web-toggle/styles'
22
+ /** Browser-local per-Session state: `1` means the switch is off. */
23
+ const STORAGE_PREFIX = 'dsh-web-toggle:off:'
24
+ /**
25
+ * Sessions already reconciled with the Host in this page. Kept outside the
26
+ * component so switching away and back neither re-runs `/webtoggle status` nor
27
+ * re-raises the "the host restarted" note; a real page reload clears it.
28
+ */
29
+ const probedSessions = new Set()
30
+ /** How long a settled note stays in the tool row. */
31
+ const NOTE_MS = 9000
32
+
33
+ const CSS = `
34
+ .dswt-root{display:inline-flex;align-items:center;gap:2px;min-width:0;max-width:100%;color:var(--dsw-alias-label-secondary);font-size:13px;font-weight:500;line-height:20px}
35
+ .dswt-root[data-off="true"]{color:var(--dsw-alias-label-secondary)}
36
+ .dswt-root[data-busy="true"]{opacity:.7}
37
+ .dswt-trigger{border-radius:var(--dsw-radius-sm,6px);height:28px;color:inherit;cursor:pointer;background:0 0;border:none;outline:none;align-items:center;gap:5px;padding:0 8px;font:inherit;font-size:13px;font-weight:500;line-height:20px;display:inline-flex}
38
+ @media (hover:hover){.dswt-trigger:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.1))}}
39
+ .dswt-trigger:focus-visible{box-shadow:0 0 0 2px var(--dsw-focus-ring-color,var(--dsw-alias-brand-primary))}
40
+ .dswt-trigger:disabled{cursor:default;opacity:.55}
41
+ .dswt-icon{position:relative;flex:none;display:inline-flex;opacity:.85}
42
+ .dswt-icon svg{width:14px;height:14px}
43
+ .dswt-root[data-off="false"] .dswt-icon{color:var(--dsw-alias-state-success-primary)}
44
+ .dswt-root[data-off="true"] .dswt-icon::after{content:"";position:absolute;left:-1px;top:50%;width:16px;height:1.5px;border-radius:1px;background:currentColor;transform:rotate(-45deg);transform-origin:center}
45
+ .dswt-label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}
46
+ .dswt-note{display:inline-flex;align-items:center;min-width:0;max-width:220px;margin-left:2px;padding:0 8px;color:var(--dsw-alias-label-secondary);font-weight:400;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
47
+ .dswt-note[data-kind="ok"]{color:var(--dsw-alias-state-success-primary)}
48
+ .dswt-note[data-kind="error"]{color:var(--dsw-alias-state-error-primary)}
49
+ `
50
+
51
+ const DICT = {
52
+ en: {
53
+ 'group.aria': 'Network switch',
54
+ 'label': 'Web',
55
+ 'title.on': 'Network is on for this task: web search, browser, MCP and shell tools can reach the internet. Click to cut them off.',
56
+ 'title.off': 'Network is off for this task: the internet-facing tools are hidden, and shell commands that would fetch anything are refused. Click to restore.',
57
+ 'title.running': 'This task is running; switch the web tools once the turn ends.',
58
+ 'note.off': 'Network off',
59
+ 'note.offTitle': 'The internet-facing tools are hidden from the next request; shell commands that would fetch anything are refused.',
60
+ 'note.on': 'Network on',
61
+ 'note.onTitle': 'The full tool list is back in this task from the next request.',
62
+ 'note.syncedOn': 'Network on',
63
+ 'note.syncedOnTitle': 'The host restarted, so this task can reach the internet again.',
64
+ 'error.noRemote': 'The command service is unavailable on this page, so the switch cannot change anything.',
65
+ 'error.noSession': 'Open a task to switch its web tools.',
66
+ 'error.commandMissing': 'The /webtoggle command is not registered, so this build cannot switch the web tools.',
67
+ 'error.failed': 'Could not switch the network: {reason}',
68
+ 'error.failedNoReason': 'the host returned no reason',
69
+ 'error.running': 'This task is running; switch the web tools after the turn ends.',
70
+ },
71
+ zh: {
72
+ 'group.aria': '联网开关',
73
+ 'label': '联网',
74
+ 'title.on': '本任务可以联网:网页搜索、浏览器、MCP、shell 都能出网。点击断网。',
75
+ 'title.off': '本任务已断网:能出网的工具都隐藏了,shell 里的联网命令会被拦。点击恢复。',
76
+ 'title.running': '当前任务正在执行,等这一轮结束后再切换联网开关。',
77
+ 'note.off': '已断网',
78
+ 'note.offTitle': '从下一次请求起,能出网的工具都被隐藏,shell 里的联网命令会被拦。',
79
+ 'note.on': '已联网',
80
+ 'note.onTitle': '完整工具列表从下一次请求起回到本任务。',
81
+ 'note.syncedOn': '已联网',
82
+ 'note.syncedOnTitle': '宿主已重启,本任务因此恢复联网。',
83
+ 'error.noRemote': '当前页面无法使用命令服务,开关改不了任何东西。',
84
+ 'error.noSession': '请先打开一个任务再切换联网工具。',
85
+ 'error.commandMissing': '/webtoggle 命令未注册(Host 半侧未生效),因此无法切换联网工具。',
86
+ 'error.failed': '切换联网开关失败:{reason}',
87
+ 'error.failedNoReason': '宿主未返回原因',
88
+ 'error.running': '当前任务正在执行,等这一轮结束后再切换联网工具。',
89
+ },
90
+ }
91
+
92
+ /** Fill `{name}` placeholders in one localized pattern. */
93
+ const format = (pattern, values) =>
94
+ pattern.replace(/\{(\w+)\}/g, (match, key) => (values[key] === undefined ? match : String(values[key])))
95
+
96
+ /** The best available message for a failed Remote result or a thrown error. */
97
+ const describeFailure = (error, t) => {
98
+ if (error !== null && typeof error === 'object') {
99
+ const details = error.details
100
+ if (details !== null && typeof details === 'object' && typeof details.reason === 'string' && details.reason !== '') {
101
+ return details.reason
102
+ }
103
+ if (typeof error.message === 'string' && error.message !== '') return error.message
104
+ }
105
+ if (typeof error === 'string' && error !== '') return error
106
+ return t('error.failedNoReason')
107
+ }
108
+
109
+ /**
110
+ * Read the state marker the Host appends to every result (`[web:on]` / `[web:off]`).
111
+ * @param text - the command result text.
112
+ * @returns `'on'`, `'off'`, or undefined when the text carries no marker.
113
+ */
114
+ const parseMarker = (text) => {
115
+ if (typeof text !== 'string') return undefined
116
+ const matched = /\[web:(on|off)\]/.exec(text)
117
+ return matched === null ? undefined : matched[1]
118
+ }
119
+
120
+ /** Storage key of one Session's remembered state. */
121
+ const storageKey = (sessionId) => STORAGE_PREFIX + sessionId
122
+
123
+ /** Read this Session's remembered state; storage can be unavailable in a locked-down page. */
124
+ const readPreference = (sessionId) => {
125
+ try {
126
+ if (typeof localStorage === 'undefined' || sessionId === undefined) return false
127
+ return localStorage.getItem(storageKey(sessionId)) === '1'
128
+ } catch (error) {
129
+ return false
130
+ }
131
+ }
132
+
133
+ /** Persist this Session's state (only "off" is stored; "on" clears the key). */
134
+ const writePreference = (sessionId, off) => {
135
+ try {
136
+ if (typeof localStorage === 'undefined' || sessionId === undefined) return
137
+ if (off) localStorage.setItem(storageKey(sessionId), '1')
138
+ else localStorage.removeItem(storageKey(sessionId))
139
+ } catch (error) {
140
+ /* storage denied: the switch stays page-scoped */
141
+ }
142
+ }
143
+
144
+ /** The globe glyph: a round window with two meridians and a latitude line. */
145
+ const globeGlyph = () =>
146
+ h(
147
+ 'svg',
148
+ { viewBox: '0 0 16 16', width: 14, height: 14, 'aria-hidden': true, focusable: false },
149
+ h('circle', { cx: 8, cy: 8, r: 5.9, fill: 'none', stroke: 'currentColor', strokeWidth: 1.4 }),
150
+ h('path', { d: 'M8 2.1c1.9 1.6 1.9 10.2 0 11.8M8 2.1c-1.9 1.6-1.9 10.2 0 11.8', fill: 'none', stroke: 'currentColor', strokeWidth: 1.2 }),
151
+ h('path', { d: 'M2.4 6.2h11.2M2.4 9.8h11.2', fill: 'none', stroke: 'currentColor', strokeWidth: 1.2 }),
152
+ )
153
+
154
+ /**
155
+ * Build the slot component over one plugin context.
156
+ * @param ctx - the Client plugin context (carries the `remote` facade).
157
+ * @returns the React component registered into `conversation.input.left`.
158
+ */
159
+ function createWebToggle(ctx) {
160
+ /** The Remote facade, read lazily because namespaces mount after apply. */
161
+ const remoteOf = () => {
162
+ try {
163
+ return ctx.get('remote')
164
+ } catch (error) {
165
+ return undefined
166
+ }
167
+ }
168
+
169
+ return function WebToggle(props) {
170
+ const t = typeof props.t === 'function' ? props.t : (key) => key
171
+ const sessionId = typeof props.sessionId === 'string' && props.sessionId !== '' ? props.sessionId : undefined
172
+ // The slot always hands over the session store hook; a deployment without it
173
+ // simply never reports a running turn.
174
+ const useSessions = typeof props.useSessions === 'function' ? props.useSessions : (selector) => selector(undefined)
175
+ const running = useSessions((state) => (state === undefined ? false : state.byId?.[sessionId]?.running === true))
176
+
177
+ const [off, setOff] = useState(() => readPreference(sessionId))
178
+ const [busy, setBusy] = useState(false)
179
+ const [note, setNote] = useState(null)
180
+ const aliveRef = useRef(true)
181
+ const busyRef = useRef(false)
182
+
183
+ useEffect(() => {
184
+ aliveRef.current = true
185
+ return () => {
186
+ aliveRef.current = false
187
+ }
188
+ }, [])
189
+
190
+ // A different Session in the same component: show that Session's state.
191
+ useEffect(() => {
192
+ setNote(null)
193
+ setOff(readPreference(sessionId))
194
+ }, [sessionId])
195
+
196
+ useEffect(() => {
197
+ if (note === null) return undefined
198
+ const timer = window.setTimeout(() => {
199
+ if (aliveRef.current) setNote(null)
200
+ }, NOTE_MS)
201
+ return () => window.clearTimeout(timer)
202
+ }, [note])
203
+
204
+ /** Show one error in the tool row. */
205
+ const fail = (text) => {
206
+ setNote({ kind: 'error', text, title: text })
207
+ return false
208
+ }
209
+
210
+ /** Commit one observed state to the button and to storage. */
211
+ const commit = (nextOff) => {
212
+ setOff(nextOff)
213
+ writePreference(sessionId, nextOff)
214
+ // The Host just answered for this Session, so a later re-mount does not need
215
+ // to ask it again.
216
+ if (sessionId !== undefined) probedSessions.add(sessionId)
217
+ }
218
+
219
+ /**
220
+ * Run one `/webtoggle` form and fold the Host's answer into the button.
221
+ * @param rawInput - `on`, `off`, or `status`.
222
+ * @param quiet - true for the mount-time probe, which must not write a note.
223
+ * @returns whether the Host confirmed a state.
224
+ */
225
+ async function invoke(rawInput, quiet = false) {
226
+ if (busyRef.current) return false
227
+ if (sessionId === undefined) return quiet ? false : fail(t('error.noSession'))
228
+ const remote = remoteOf()
229
+ // The generated stub counts three wire parameters: agentId, line, submittedAttachments.
230
+ const commands = remote === undefined ? undefined : remote.commands
231
+ if (commands === undefined || typeof commands.execute !== 'function') {
232
+ return quiet ? false : fail(t('error.noRemote'))
233
+ }
234
+ busyRef.current = true
235
+ if (!quiet) {
236
+ setBusy(true)
237
+ setNote(null)
238
+ }
239
+ try {
240
+ const result = await commands.execute(sessionId, `/webtoggle ${rawInput}`, [])
241
+ if (!aliveRef.current) return false
242
+ if (result === undefined || result.ok !== true) {
243
+ const reason = result === undefined ? t('error.failedNoReason') : describeFailure(result.error, t)
244
+ return quiet ? false : fail(format(t('error.failed'), { reason }))
245
+ }
246
+ // `undefined` means the Host resolved no command with that name.
247
+ const execution = result.value
248
+ if (execution === undefined) return quiet ? false : fail(t('error.commandMissing'))
249
+ const outcome = execution.result
250
+ if (outcome === undefined || outcome.kind !== 'success') {
251
+ // The Host's own text explains refusals precisely (running, no web tools),
252
+ // so it is shown verbatim.
253
+ const text = typeof outcome?.text === 'string' && outcome.text !== '' ? outcome.text : t('error.failedNoReason')
254
+ return quiet ? false : fail(text)
255
+ }
256
+ const marker = parseMarker(outcome.text)
257
+ if (marker !== undefined) commit(marker === 'off')
258
+ if (quiet) return marker !== undefined
259
+ const nextOff = marker === undefined ? readPreference(sessionId) : marker === 'off'
260
+ setNote(
261
+ nextOff
262
+ ? { kind: 'ok', text: t('note.off'), title: t('note.offTitle') }
263
+ : { kind: 'ok', text: t('note.on'), title: t('note.onTitle') },
264
+ )
265
+ return true
266
+ } catch (error) {
267
+ return aliveRef.current && !quiet ? fail(format(t('error.failed'), { reason: describeFailure(error, t) })) : false
268
+ } finally {
269
+ busyRef.current = false
270
+ if (aliveRef.current) setBusy(false)
271
+ }
272
+ }
273
+
274
+ // The Host forgets the switch when DSH restarts while this browser remembers it.
275
+ // One `/webtoggle status` reconciles that case; a remembered "on" needs no probe,
276
+ // and a Session already probed in this page is not probed again — switching away
277
+ // and back must not fire the command or a note every time.
278
+ useEffect(() => {
279
+ if (sessionId === undefined || running) return undefined
280
+ if (!readPreference(sessionId)) return undefined
281
+ if (probedSessions.has(sessionId)) return undefined
282
+ let cancelled = false
283
+ const timer = window.setTimeout(async () => {
284
+ const remote = remoteOf()
285
+ const commands = remote === undefined ? undefined : remote.commands
286
+ if (cancelled || commands === undefined || typeof commands.execute !== 'function') return
287
+ probedSessions.add(sessionId)
288
+ const before = readPreference(sessionId)
289
+ const answered = await invoke('status', true)
290
+ if (cancelled || !answered || !aliveRef.current) return
291
+ const after = readPreference(sessionId)
292
+ // Only a correction deserves a note: when the Host confirms the remembered
293
+ // "off", the button already shows it and silence is the honest answer.
294
+ if (before && !after) setNote({ kind: 'ok', text: t('note.syncedOn'), title: t('note.syncedOnTitle') })
295
+ }, 0)
296
+ return () => {
297
+ cancelled = true
298
+ window.clearTimeout(timer)
299
+ }
300
+ }, [sessionId, running])
301
+
302
+ /** Flip the switch for this Session. */
303
+ const toggle = () => {
304
+ if (busyRef.current) return
305
+ if (sessionId === undefined) {
306
+ fail(t('error.noSession'))
307
+ return
308
+ }
309
+ if (running) {
310
+ fail(t('error.running'))
311
+ return
312
+ }
313
+ invoke(off ? 'on' : 'off')
314
+ }
315
+
316
+ const title = running ? t('title.running') : off ? t('title.off') : t('title.on')
317
+
318
+ return h(
319
+ 'div',
320
+ { className: 'dswt-root', 'data-off': off ? 'true' : 'false', 'data-busy': busy ? 'true' : 'false', role: 'group', 'aria-label': t('group.aria') },
321
+ h(
322
+ 'button',
323
+ {
324
+ type: 'button',
325
+ className: 'dswt-trigger',
326
+ 'aria-pressed': off ? 'false' : 'true',
327
+ 'aria-label': t('group.aria'),
328
+ title: busy ? t('title.running') : title,
329
+ disabled: busy || running,
330
+ onMouseDown: (event) => event.preventDefault(),
331
+ onClick: toggle,
332
+ },
333
+ h('span', { className: 'dswt-icon', 'aria-hidden': true }, globeGlyph()),
334
+ h('span', { className: 'dswt-label' }, t('label')),
335
+ ),
336
+ note === null
337
+ ? null
338
+ : h('span', { className: 'dswt-note', 'data-kind': note.kind, 'aria-live': 'polite', title: note.title }, note.text),
339
+ )
340
+ }
341
+ }
342
+
343
+ return {
344
+ // `remote` and `remote.commands` gate activation until the Host Remotes this
345
+ // control calls are mounted.
346
+ inject: ['slots', 'locale', 'remote', 'remote.commands'],
347
+ apply(ctx) {
348
+ ctx.effect(() => {
349
+ if (typeof document === 'undefined') return () => {}
350
+ const selector = 'style[data-plugin-css=' + JSON.stringify(STYLE_ID) + ']'
351
+ if (document.querySelector(selector) !== null) return () => {}
352
+ const tag = document.createElement('style')
353
+ tag.dataset.plugin = 'dsh-web-toggle'
354
+ tag.dataset.pluginCss = STYLE_ID
355
+ tag.textContent = CSS
356
+ document.head.appendChild(tag)
357
+ return () => {
358
+ tag.remove()
359
+ }
360
+ }, 'web-toggle: stylesheet')
361
+
362
+ ctx.effect(() => ctx.locale.register(NS, DICT), 'web-toggle: dictionaries')
363
+
364
+ const t = typeof ctx.locale.bind === 'function' ? ctx.locale.bind(NS) : (key) => key
365
+ const WebToggle = createWebToggle(ctx)
366
+ ctx.slots.inject('conversation.input.left', () =>
367
+ ctx.slots.register(
368
+ {
369
+ name: 'conversation.input.left',
370
+ id: 'web-toggle',
371
+ order: 11,
372
+ locale: NS,
373
+ label: () => t('group.aria'),
374
+ },
375
+ WebToggle,
376
+ ),
377
+ )
378
+ },
379
+ }
380
+ },
381
+ })
@@ -0,0 +1,11 @@
1
+ # web-toggle bundle: one row that mounts the Host half and its browser half.
2
+ #
3
+ # Host half (index.js): registers /webtoggle and denies web_search / web_fetch for
4
+ # one agent through the scope-bound tools.restrict(), keeping the exact disposer;
5
+ # the first admitted step after a change restarts the request series so the new
6
+ # tool catalog is not announced as deferred additions.
7
+ # Browser half (client.js): registers the toggle into conversation.input.left and
8
+ # drives it through the existing commands Remote.
9
+ - insert:
10
+ - id: web-toggle
11
+ name: 'dsh-web-toggle'
package/docs/DETAIL.md ADDED
@@ -0,0 +1,67 @@
1
+ # 联网开关
2
+
3
+ 输入框工具栏上的一个小开关,只干一件事:控制**当前会话**的模型能不能看到 `web_search` / `web_fetch`。
4
+
5
+ ## 用法
6
+
7
+ - 工具栏左侧的「联网」按钮:亮着 = 开,图标被斜线划掉 = 关。
8
+ - 点一下切换。也可以在输入框里敲命令:
9
+
10
+ | 命令 | 作用 |
11
+ | --- | --- |
12
+ | `/webtoggle` | 切换本会话的联网开关 |
13
+ | `/webtoggle off` | 关(幂等:重复关不会叠加限制) |
14
+ | `/webtoggle on` | 开 |
15
+ | `/webtoggle status` | 只看当前状态,不改 |
16
+
17
+ 命令结果末尾带一个机器可读标记(`[web:on]` / `[web:off]`),按钮用它同步真实状态。
18
+
19
+ ## 行为
20
+
21
+ - 关闭后,本会话的 Agent 上下文被 `tools.restrict({ allow: [...本地工具 + ops_bash] })` 加上遮罩:下一次请求的工具声明里只剩白名单里的名字,其余(网页搜索、浏览器、MCP、视频/生图、子代理、插件管理、定时任务)一律消失;模型硬调用只会得到 unknown tool。
22
+ - `ops_bash` 属于双用途工具,因此不隐藏而是加一道 `tools.guard()`:命令文本命中联网特征(`curl`/`wget`/`ssh`/`git clone`/`pnpm add`/`pip install`/`http(s)://`/UNC 共享/导入 `http`,`net`,`tls` 模块等)就在执行前被拒绝,本地命令照常跑。guard 是与 restrict 同作用域的,恢复时一并撤销。
23
+ - 用**白名单**而不是 deny 两三个名字是有意的:`ops_bash` 可以 `curl`、浏览器工具能开页面、MCP 能转发请求,deny 少数几个永远漏。白名单默认关门,将来新插件加的工具也进不来,除非显式加名字。
24
+ - 白名单只取"工具目录里真实存在的名字"(`tools.view().restrictableNames`),所以某个插件没装时不会因为 `restrict()` 报 unknown tool 而整体失败。
25
+ - 恢复时调用当时存下的那个 disposer,遮罩被精确撤销,工具列表原样回来。
26
+ - 状态按**会话**记录,互不影响:关掉 A 会话不会影响 B 会话,也不影响其他会话的本地工作。
27
+ - 工具列表变了会重建请求序列(`agent/pre-step` → `startsRequestSeries`),避免新声明被上游当成「延迟追加」。
28
+
29
+ ## 性能
30
+
31
+ - Host 半侧:一次切换只做一次 `view()` 读取 + 约 34 个名字的集合过滤;平时只有两个事件监听器,`agent/pre-step` 里也只是 `Set.has` 一次。
32
+ - 客户端:一个小组件,状态不变就不重渲染;本地记忆一次 `localStorage` 读取;不轮询。唯一的定时器是"浏览器记着关"时那一次 0ms 探针,同一页面每个会话最多一次。
33
+
34
+ ## 边界与限制
35
+
36
+ - **轮次进行中不改**:任务正在跑时点按钮会直接拒绝并提示,等这一轮结束再切。理由是不会在轮次中途换工具集(那会让同一轮的前后请求声明不一致)。
37
+ - **是工具层的门,不是网络层的墙**:DSH 内核没有"按会话断网"的能力(`dsh-sandbox-local` 只约束文件系统,没有网络规则),所以这层挡的是"手里的工具",不是 TCP 连接。
38
+ - 因此仍有三个洞:① shell 过滤是字面匹配,精心伪装的命令能绕(要更狠就只能连 shell 一起隐藏);② 关之前已经跑起来的后台任务(例如 `curl`)不会自动断,用 `job_list` + `job_kill` 收尾;③ `run_code` 是内核保留名字,`restrict()` 不接受,PTC 模式下它仍可见(它自身没有网络 API,但能起的子代理是否受限取决于内核);④ 真要在系统层断绝,只能在无网 VM/容器里跑 DSH。
39
+ - **只影响被关的那一个会话**:其余会话、以及本会话的本地工具(文件、检索、计划、记忆、技能)照常工作。
40
+ - **重启重置**:DSH 重启后 Host 侧状态清零(工具恢复可见)。按钮挂载时如果浏览器记着「关」,会向 Host 探一次 `/webtoggle status` 把显示纠正过来,因此不会出现「明明开着却显示关」。
41
+ - 探针每个会话在一个页面生命周期内只跑一次(模块级 `probedSessions`)。切到别的会话再切回来,既不重发命令也不弹提示;只有真出现「记忆为关、宿主已开」时提示一次。
42
+ - 宿主确认仍是关闭时保持沉默——按钮本来就是灭的,再弹一句「仍是关闭」只是噪音。
43
+ - 会话销毁会撤销遮罩并清理记录,限制不会泄漏到别的会话。
44
+
45
+ ## 相关实现
46
+
47
+ - `index.js`:`/webtoggle` 命令、`tools.restrict()` 遮罩与 disposer 管理、请求序列重建、会话销毁清理。
48
+ - `client.js`:`conversation.input.left` 槽位组件、按会话铭记的显示状态、`commands.execute` 调用。
49
+
50
+ ## 拒绝文案为什么写成指令
51
+
52
+ `OFFLINE_NOTICE`(`index.js` 顶部)追加在每一条 guard 拒绝理由末尾。它刻意不是"这条命令被拦了"这种描述句,而是四段式指令:
53
+
54
+ 1. **先给规则**:本会话不允许使用一切形式的联网工具——范围是"全部联网工具",不是"这一条命令"。
55
+ 2. **封掉绕路**:换工具、写脚本、编码后执行、起子进程找替代通道,都算同一个动作。
56
+ 3. **给出口**:真需要联网就停下、向用户说明、请用户暂时打开开关。
57
+ 4. **给误判通道**:怀疑误判也走第 3 条,不要自己试。
58
+
59
+ 理由:模型看到"被拦了"会倾向于换一种写法再试一次;看到"规则 + 禁止换路 + 唯一出口"才会停下来找人。中英各一份,跟着会话语言走不了(命令结果不带语言上下文),所以两条都给。
60
+
61
+ ## 命令过滤的三层(`index.js`)
62
+
63
+ 1. **字面匹配**:`NETWORK_COMMAND` 认客户端、包管理联网子命令、URL、UNC、解释器的网络模块。
64
+ 2. **去伪装再匹配**:`squashQuotes()` 去掉 `'` `"` `` ` `` `^` `\` `+` 与 `${IFS}`,把 `so''cket`、`"cur""l"`、`'so'+'cket'` 还原成真名后再匹配一次。
65
+ 3. **看它要执行的文件**:`inspectScripts()` 对解释器 + 脚本扩展名的组合,按 workdir → 会话目录 → 进程目录解析并读文件(≤256 KB,一层递归);`inspectPackageScript()` 对 `npm run x` / `pnpm x` 读 `package.json` 的 `scripts.x`,同样匹配并检查其中引用的脚本。
66
+
67
+ 读不到文件一律放行:读不到的东西也跑不起来,而 fail-closed 会让正常工程挂掉。开销:断网时每次 `ops_bash` 最多多读一个几百 KB 以内的文件,不做目录遍历。