dsh-web-toggle 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +96 -2
- package/client.js +381 -0
- package/cordis.patch.yml +11 -0
- package/docs/DETAIL.md +67 -0
- package/docs/REDTEAM.md +212 -0
- package/docs/VERIFY.md +66 -0
- package/icon.svg +8 -0
- package/index.js +554 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +51 -4
- package/scripts/sync-to-profile.mjs +50 -0
- package/tests/client.test.mjs +355 -0
- package/tests/host.test.mjs +395 -0
package/index.js
ADDED
|
@@ -0,0 +1,554 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host half of the web-toggle bundle: a per-Session network switch.
|
|
3
|
+
*
|
|
4
|
+
* Registers `/webtoggle [on|off|status]`. Turning the switch off keeps ONLY the
|
|
5
|
+
* tools that cannot reach the network, through one `agent.ctx.tools.restrict()`
|
|
6
|
+
* call on that Agent (scope-bound, so it never leaks to another Session), and
|
|
7
|
+
* keeps the exact disposer that lifts it. Turning it on calls that disposer.
|
|
8
|
+
*
|
|
9
|
+
* Why an allowlist instead of denying `web_search`/`web_fetch`: those are only the
|
|
10
|
+
* official network tools. A browser tool can open a page, an MCP server can forward
|
|
11
|
+
* a request. Keeping the local tools and hiding everything else is the closed form:
|
|
12
|
+
* a tool a later plugin adds stays hidden until it is named here.
|
|
13
|
+
*
|
|
14
|
+
* `ops_bash` is the one dual-use tool that stays: it is the only way to do local work
|
|
15
|
+
* (build, test, move files), so it is kept visible and fenced by a command guard that
|
|
16
|
+
* refuses calls which look like network traffic. That guard is a filter, not a wall —
|
|
17
|
+
* see README for the limits.
|
|
18
|
+
*
|
|
19
|
+
* The tool catalog changes under a live Session, so the next admitted step starts
|
|
20
|
+
* a new request series: the recorded series can no longer describe the catalog,
|
|
21
|
+
* and a rebuilt series sends the new declarations instead of "deferred additions".
|
|
22
|
+
*
|
|
23
|
+
* The Host half has no locale service, so command text is bilingual.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { readFileSync, statSync } from 'node:fs'
|
|
27
|
+
import { isAbsolute, resolve } from 'node:path'
|
|
28
|
+
|
|
29
|
+
export const inject = ['commands', 'agents', 'tools']
|
|
30
|
+
|
|
31
|
+
/** The command name. */
|
|
32
|
+
const COMMAND = 'webtoggle'
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The tools the switch leaves visible: every one of them only touches this machine.
|
|
36
|
+
* Files, search, planning, context bookkeeping, skills, jobs. Anything that can open
|
|
37
|
+
* a socket — `ops_bash`, the browser tools, MCP servers, media generation, sub-agents,
|
|
38
|
+
* the plugin manager, scheduled tasks — is deliberately absent, so "off" cannot leak.
|
|
39
|
+
*/
|
|
40
|
+
const LOCAL_TOOLS = [
|
|
41
|
+
'acp_cache',
|
|
42
|
+
'acp_read_original_image',
|
|
43
|
+
'acp_status',
|
|
44
|
+
'ask_user_question',
|
|
45
|
+
'compress',
|
|
46
|
+
'create_goal',
|
|
47
|
+
'create_skill',
|
|
48
|
+
'create_worktree',
|
|
49
|
+
'decompress',
|
|
50
|
+
'edit',
|
|
51
|
+
'get_goal',
|
|
52
|
+
'job_kill',
|
|
53
|
+
'job_list',
|
|
54
|
+
'job_output',
|
|
55
|
+
'list_agents',
|
|
56
|
+
'list_subagent_models',
|
|
57
|
+
'load_workspace_dependencies',
|
|
58
|
+
'ops_discover_tools',
|
|
59
|
+
'ops_glob',
|
|
60
|
+
'ops_grep',
|
|
61
|
+
'ops_inspect_local_file',
|
|
62
|
+
'present',
|
|
63
|
+
'read_animation',
|
|
64
|
+
'read_image',
|
|
65
|
+
'remember',
|
|
66
|
+
'schedule_list',
|
|
67
|
+
'schedule_view',
|
|
68
|
+
'search_context',
|
|
69
|
+
'skill',
|
|
70
|
+
'switch_session_preset',
|
|
71
|
+
'todo_write',
|
|
72
|
+
'update_goal',
|
|
73
|
+
'working_directory',
|
|
74
|
+
'write',
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Dual-use tools that stay visible while the switch is off, each fenced by a guard
|
|
79
|
+
* instead of being hidden: `ops_bash` still runs local commands, but a command that
|
|
80
|
+
* looks like network traffic is refused before it starts.
|
|
81
|
+
*/
|
|
82
|
+
/**
|
|
83
|
+
* Every denial ends with this. It is written as an instruction, not a description:
|
|
84
|
+
* the model must not go looking for another route to the network (a different tool,
|
|
85
|
+
* a script file, an encoded payload, a child process all count), and when it genuinely
|
|
86
|
+
* needs the network it should stop and ask the user to flip the switch back on.
|
|
87
|
+
*/
|
|
88
|
+
const OFFLINE_NOTICE =
|
|
89
|
+
'规则:本会话暂时不允许使用一切形式的联网工具。不要换别的工具、不要写脚本或编码后执行、' +
|
|
90
|
+
'不要起子进程去找替代通道——开关打开之前这里的任何联网尝试都会被拦下。真的需要联网时,' +
|
|
91
|
+
'停下来向用户说明「需要联网」,请用户暂时打开开关;如果怀疑是误判,也照此处理。 / ' +
|
|
92
|
+
'Rule: this task currently allows no networked tools of any kind. Do not reach for another ' +
|
|
93
|
+
'tool, do not write a script or encode a payload to run, do not spawn a child process looking ' +
|
|
94
|
+
'for a side channel — every networked attempt is blocked here until the switch is on. If you ' +
|
|
95
|
+
'genuinely need the network, stop and tell the user you need it, and ask them to turn the ' +
|
|
96
|
+
'switch back on for a while. Do the same if you suspect a false positive.'
|
|
97
|
+
|
|
98
|
+
const GUARDED_TOOLS = ['ops_bash']
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Words that mean "this command wants the network": binaries, schemes, package fetches,
|
|
102
|
+
* and the module names an interpreter needs before it can open a socket.
|
|
103
|
+
*
|
|
104
|
+
* Two rules were deliberately removed after a red-team pass, because they fired on
|
|
105
|
+
* ordinary local work: a bare dotted quad (version numbers, build ids, log fragments)
|
|
106
|
+
* and `asyncio` itself (`asyncio.sleep` is local; only `open_connection` leaves).
|
|
107
|
+
*/
|
|
108
|
+
const NETWORK_COMMAND = new RegExp(
|
|
109
|
+
[
|
|
110
|
+
// 命令行客户端
|
|
111
|
+
String.raw`\b(curl|wget|nc|netcat|ncat|telnet|ssh|scp|sftp|ftp|lftp|socat|rsync|arp|nslookup|dig|ping|tracert|traceroute|whois)\b`,
|
|
112
|
+
// PowerShell / .NET:拆段拼 URL 时类型名仍会露出来
|
|
113
|
+
String.raw`\b(Invoke-WebRequest|Invoke-RestMethod|Start-BitsTransfer|bitsadmin|certutil|mshta|DownloadString|DownloadFile|WebClient|HttpClient|WebRequest|TcpClient|UdpClient|System\.Net|EncodedCommand)\b`,
|
|
114
|
+
// 联网式仓库操作
|
|
115
|
+
String.raw`\b(git|hg)\s+(clone|fetch|pull|push|ls-remote|archive|submodule)\b`,
|
|
116
|
+
// 包管理器:只列会走 registry 的子命令,run/test/build/ls 这类本地命令不受影响
|
|
117
|
+
String.raw`\b(npm|pnpm|yarn|bun)\s+(i|install|add|remove|rm|uninstall|update|up|upgrade|ci|pack|publish|view|info|show|search|audit|outdated|login|logout|adduser|whoami|token|dist-tag|deprecate|unpublish|star|stars|owner|access|org|team|repo|docs|home|ping|fetch|fund|cache|exec|dlx|create)\b`,
|
|
118
|
+
String.raw`\b(pip|pip3|pipx|poetry|uv|cargo|go|gem|composer|dotnet)\s+(install|get|add|fetch|publish|index|download|update)\b`,
|
|
119
|
+
String.raw`\bgh\s+(api|repo|release|pr|issue|auth|workflow|search|gist)\b`,
|
|
120
|
+
// 脚本层:导入网络模块
|
|
121
|
+
String.raw`(require|import|from)\s*\(?\s*['"](node:)?(https?|net|tls|dns|dgram|undici|ws|child_process|aiohttp|httpx)['"]`,
|
|
122
|
+
String.raw`\bimport\s+(socket|ssl|ftplib|smtplib|poplib|imaplib|telnetlib|xmlrpc|webbrowser|http\.client|urllib|requests)\b`,
|
|
123
|
+
String.raw`\bfrom\s+(socket|ssl|ftplib|smtplib|poplib|imaplib|telnetlib|xmlrpc|webbrowser|urllib|http)\s+import\b`,
|
|
124
|
+
// 直接调网络函数(不写 import 也能连)
|
|
125
|
+
String.raw`\b(socket\.socket|create_connection|open_connection|getaddrinfo|gethostbyname|wrap_socket|create_default_context|SSLSocket)\b`,
|
|
126
|
+
String.raw`\b(urllib|http\.client|httpx|aiohttp|axios|node-fetch|XMLHttpRequest)\b`,
|
|
127
|
+
// 动态导入与解码载荷:`__import__('so'+'cket')`、`b64decode(...)` 都是藏名字的写法
|
|
128
|
+
String.raw`__import__\s*\(\s*['"]?(socket|ssl|urllib|requests|http)`,
|
|
129
|
+
String.raw`\b(b64decode|unhexlify|fromhex)\b`,
|
|
130
|
+
// 编码载荷再交给解释器
|
|
131
|
+
String.raw`\bbase64\s+(-d|--decode|-[dD])\b[^|]*\|\s*(ba|da|z)?sh\b`,
|
|
132
|
+
String.raw`\bbase64\s+(-d|--decode|-[dD])\b[^|]*\|\s*(xargs|eval|node|python|perl)\b`,
|
|
133
|
+
// URL / UNC / SMB
|
|
134
|
+
String.raw`\b(https?|ftp|wss?)://`,
|
|
135
|
+
String.raw`\\\\[A-Za-z0-9_.$-]+\b`,
|
|
136
|
+
String.raw`\bnet\s+use\b|\bNew-PSDrive\b`,
|
|
137
|
+
].join('|'),
|
|
138
|
+
'i',
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The same keyword test with quoting tricks undone: `import so''cket`, `"cur""l"`,
|
|
143
|
+
* `c\url` and `${IFS}` separated words all collapse to the literal the shell or the
|
|
144
|
+
* interpreter ends up executing.
|
|
145
|
+
* @param text - one command or script body.
|
|
146
|
+
* @returns the collapsed form used for a second match pass.
|
|
147
|
+
*/
|
|
148
|
+
const squashQuotes = (text) =>
|
|
149
|
+
text
|
|
150
|
+
.replace(/['"`^\\+]/g, '')
|
|
151
|
+
.replace(/\$\{?ifs\}?/gi, '')
|
|
152
|
+
.replace(/\s+/g, ' ')
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Does this text look like network traffic?
|
|
156
|
+
* @param text - a command line or a script body.
|
|
157
|
+
* @returns true when either the literal or the de-quoted form matches.
|
|
158
|
+
*/
|
|
159
|
+
const looksNetworked = (text) => NETWORK_COMMAND.test(text) || NETWORK_COMMAND.test(squashQuotes(text))
|
|
160
|
+
|
|
161
|
+
/** Scripts a shell can hand to an interpreter, by extension. */
|
|
162
|
+
const SCRIPT_EXT = /\.(py|pyw|js|mjs|cjs|ts|mts|cts|sh|zsh|bash|ps1|psm1|rb|pl|php|bat|cmd)$/i
|
|
163
|
+
|
|
164
|
+
/** Interpreters that take a file argument. */
|
|
165
|
+
const INTERPRETER =
|
|
166
|
+
/(^|[\s;&|(])(python3?|py|node|nodejs|bun|deno|ruby|perl|php|bash|sh|zsh|pwsh|powershell|source)(?=[\s;&|)]|$)/i
|
|
167
|
+
|
|
168
|
+
/** Read at most this much of a script before giving up (a huge file is not a script we fence). */
|
|
169
|
+
const MAX_SCRIPT_BYTES = 256 * 1024
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Split a command line into argument-ish tokens, keeping quoted runs together.
|
|
173
|
+
* @param command - the raw command.
|
|
174
|
+
* @returns the tokens with their quotes removed.
|
|
175
|
+
*/
|
|
176
|
+
function tokensOf(command) {
|
|
177
|
+
const out = []
|
|
178
|
+
const re = /"([^"]*)"|'([^']*)'|(\S+)/g
|
|
179
|
+
let match
|
|
180
|
+
while ((match = re.exec(command)) !== null) out.push(match[1] ?? match[2] ?? match[3])
|
|
181
|
+
return out
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Files in this command line that look like scripts.
|
|
186
|
+
* @param command - the raw command.
|
|
187
|
+
* @returns one entry per candidate path.
|
|
188
|
+
*/
|
|
189
|
+
function scriptRefs(command) {
|
|
190
|
+
const refs = []
|
|
191
|
+
for (const token of tokensOf(command)) {
|
|
192
|
+
const text = token.replace(/^['"]|['"]$/g, '')
|
|
193
|
+
if (text.length === 0 || text.startsWith('-')) continue
|
|
194
|
+
if (SCRIPT_EXT.test(text)) refs.push(text)
|
|
195
|
+
}
|
|
196
|
+
return refs
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Read a script a command is about to run, resolving it against the directories the
|
|
201
|
+
* call could be using. Returns undefined when nothing readable is found, in which case
|
|
202
|
+
* the call is allowed: a fence that fails closed on an unreadable path would break
|
|
203
|
+
* ordinary work, and a script that is not on disk cannot run either.
|
|
204
|
+
* @param exec - the pending execution, for `workdir` and the Session directory.
|
|
205
|
+
* @param ref - the path from the command line.
|
|
206
|
+
* @returns the script text, or undefined.
|
|
207
|
+
*/
|
|
208
|
+
function readScript(exec, ref) {
|
|
209
|
+
const bases = []
|
|
210
|
+
const args = exec.arguments
|
|
211
|
+
if (args !== null && typeof args === 'object' && typeof args.workdir === 'string' && args.workdir !== '')
|
|
212
|
+
bases.push(args.workdir)
|
|
213
|
+
const cwd = exec.agent?.session?.cwd
|
|
214
|
+
if (typeof cwd === 'string' && cwd !== '') bases.push(cwd)
|
|
215
|
+
bases.push(process.cwd())
|
|
216
|
+
for (const base of bases) {
|
|
217
|
+
const path = isAbsolute(ref) ? ref : resolve(base, ref)
|
|
218
|
+
try {
|
|
219
|
+
if (statSync(path).size > MAX_SCRIPT_BYTES) return ''
|
|
220
|
+
return readFileSync(path, 'utf8')
|
|
221
|
+
} catch {
|
|
222
|
+
continue
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return undefined
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Inspect the scripts a command line is about to run, one level deep, because writing
|
|
230
|
+
* a script and running it was the cheapest way around a text-only fence.
|
|
231
|
+
* @param exec - the pending execution.
|
|
232
|
+
* @param command - a command line or the body of another script.
|
|
233
|
+
* @param depth - how many hops are still allowed.
|
|
234
|
+
* @returns a denial reason, or undefined.
|
|
235
|
+
*/
|
|
236
|
+
function inspectScripts(exec, command, depth = 0) {
|
|
237
|
+
if (!INTERPRETER.test(command) && !/(^|[\s;&|])[./]/.test(command)) return undefined
|
|
238
|
+
for (const ref of scriptRefs(command)) {
|
|
239
|
+
const text = readScript(exec, ref)
|
|
240
|
+
if (text === undefined || text === '') continue
|
|
241
|
+
if (looksNetworked(text)) return `本会话已断网:脚本 ${ref} 里含联网调用,执行前被拦下。`
|
|
242
|
+
if (depth < 1) {
|
|
243
|
+
const nested = inspectScripts(exec, text, depth + 1)
|
|
244
|
+
if (nested !== undefined) return nested
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return undefined
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** `npm run x` / `pnpm x` / `yarn x` / `bun x`. */
|
|
251
|
+
const PACKAGE_SCRIPT = /(?:^|[\s;&|(])npm\s+(?:run|run-script)\s+([^\s;&|]+)|(?:^|[\s;&|(])(?:pnpm|yarn|bun)\s+(?:run\s+)?([^\s;&|]+)/i
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Read a script body out of the nearest package.json.
|
|
255
|
+
* @param exec - the pending execution, for `workdir` and the Session directory.
|
|
256
|
+
* @param name - the script name.
|
|
257
|
+
* @returns the body, or undefined when no package.json names it.
|
|
258
|
+
*/
|
|
259
|
+
function packageScriptBody(exec, name) {
|
|
260
|
+
const args = exec.arguments
|
|
261
|
+
const bases = []
|
|
262
|
+
if (args !== null && typeof args === 'object' && typeof args.workdir === 'string' && args.workdir !== '')
|
|
263
|
+
bases.push(args.workdir)
|
|
264
|
+
const cwd = exec.agent?.session?.cwd
|
|
265
|
+
if (typeof cwd === 'string' && cwd !== '') bases.push(cwd)
|
|
266
|
+
bases.push(process.cwd())
|
|
267
|
+
for (const base of bases) {
|
|
268
|
+
try {
|
|
269
|
+
const file = resolve(base, 'package.json')
|
|
270
|
+
if (statSync(file).size > MAX_SCRIPT_BYTES) continue
|
|
271
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8'))
|
|
272
|
+
const body = parsed?.scripts?.[name]
|
|
273
|
+
if (typeof body === 'string') return body
|
|
274
|
+
} catch {
|
|
275
|
+
continue
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return undefined
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* `npm run deploy` where deploy is `curl ...` is the same request as `curl ...`,
|
|
283
|
+
* only one indirection away. Look the body up and apply the same rules to it.
|
|
284
|
+
* @param exec - the pending execution.
|
|
285
|
+
* @param command - the command line.
|
|
286
|
+
* @returns a denial reason, or undefined.
|
|
287
|
+
*/
|
|
288
|
+
function inspectPackageScript(exec, command) {
|
|
289
|
+
const match = PACKAGE_SCRIPT.exec(command)
|
|
290
|
+
if (match === null) return undefined
|
|
291
|
+
const name = match[1] ?? match[2]
|
|
292
|
+
if (typeof name !== 'string' || name.startsWith('-')) return undefined
|
|
293
|
+
const body = packageScriptBody(exec, name)
|
|
294
|
+
if (typeof body !== 'string') return undefined
|
|
295
|
+
if (looksNetworked(body)) return `本会话已断网:脚本 ${name} 里含联网调用,执行前被拦下。`
|
|
296
|
+
const nested = inspectScripts(exec, body)
|
|
297
|
+
if (nested !== undefined) return nested
|
|
298
|
+
return undefined
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Short machine marker appended to every result text, so the browser half reads state without parsing prose. */
|
|
302
|
+
const markerOf = (off) => `[web:${off ? 'off' : 'on'}]`
|
|
303
|
+
|
|
304
|
+
/** Render one thrown value as a short message. */
|
|
305
|
+
const messageOf = (error) => (error instanceof Error ? error.message : String(error))
|
|
306
|
+
|
|
307
|
+
/** Read a value, treating a throw as absent (a service may detach mid-call). */
|
|
308
|
+
const safely = (read) => {
|
|
309
|
+
try {
|
|
310
|
+
return read()
|
|
311
|
+
} catch {
|
|
312
|
+
return undefined
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Mount the `/webtoggle` command and the series-restart listener.
|
|
318
|
+
* @param ctx - the plugin context.
|
|
319
|
+
*/
|
|
320
|
+
export function apply(ctx) {
|
|
321
|
+
/**
|
|
322
|
+
* Sessions that are switched off: `sessionId -> { agent, dispose, disposeGuard }`.
|
|
323
|
+
* A row that exists for THIS agent means "off"; the disposers are the only things
|
|
324
|
+
* that lift the restriction and the guard, so the row and the Agent lifetime stay
|
|
325
|
+
* in step.
|
|
326
|
+
*/
|
|
327
|
+
const offSessions = new Map()
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Refuse one guarded call when the command looks like network traffic.
|
|
331
|
+
* Runs before dispatch (the kernel's `tools.guard()`), only while the switch is off,
|
|
332
|
+
* and only for `GUARDED_TOOLS`. It fails closed: a guarded call whose arguments
|
|
333
|
+
* carry no readable command is refused rather than guessed through.
|
|
334
|
+
* @param exec - the pending execution (`{ name, arguments, agent, ... }`).
|
|
335
|
+
* @returns a denial reason, or undefined to let the call through.
|
|
336
|
+
*/
|
|
337
|
+
function networkGuard(exec) {
|
|
338
|
+
if (exec === null || typeof exec !== 'object') return undefined
|
|
339
|
+
if (!GUARDED_TOOLS.includes(exec.name)) return undefined
|
|
340
|
+
const args = exec.arguments
|
|
341
|
+
const command = args !== null && typeof args === 'object' ? args.command : undefined
|
|
342
|
+
if (typeof command !== 'string') {
|
|
343
|
+
return `本会话已断网:这条工具调用没有可检查的命令文本,为稳妥起见拒绝执行。${OFFLINE_NOTICE}`
|
|
344
|
+
}
|
|
345
|
+
if (looksNetworked(command)) {
|
|
346
|
+
return `本会话已断网:这条命令看起来会联网(下载、远程连接或网络 URL),已被拦下。本地命令照常可以执行。${OFFLINE_NOTICE}`
|
|
347
|
+
}
|
|
348
|
+
// 写脚本再执行原本是最省事的绕法:命令本身没有网络词,脚本里有。
|
|
349
|
+
const script = inspectScripts(exec, command)
|
|
350
|
+
if (script !== undefined) return `${script}${OFFLINE_NOTICE}`
|
|
351
|
+
const packaged = inspectPackageScript(exec, command)
|
|
352
|
+
if (packaged !== undefined) return `${packaged}${OFFLINE_NOTICE}`
|
|
353
|
+
return undefined
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Sessions whose next admitted step must start a new request series, because the
|
|
358
|
+
* tool catalog changed under them. Keyed by Session id, which outlives Agent
|
|
359
|
+
* re-creation.
|
|
360
|
+
*/
|
|
361
|
+
const pendingSeries = new Set()
|
|
362
|
+
|
|
363
|
+
// Waterfall listener: take the downstream decision first, so every other listener
|
|
364
|
+
// keeps its say, and only wrap the result for a session whose catalog changed.
|
|
365
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
366
|
+
const decision = await next()
|
|
367
|
+
const agent = payload?.agent
|
|
368
|
+
if (agent === undefined || agent.session === undefined) return decision
|
|
369
|
+
if (decision?.kind !== 'enter') return decision
|
|
370
|
+
if (!pendingSeries.has(agent.session.id)) return decision
|
|
371
|
+
// A step the loop will abandon (cancelled, or an empty admission) never becomes a
|
|
372
|
+
// request, so consuming the mark there would silently drop the series restart.
|
|
373
|
+
if (payload.signal?.aborted === true) return decision
|
|
374
|
+
if (Array.isArray(decision.messages) && decision.messages.length === 0) return decision
|
|
375
|
+
pendingSeries.delete(agent.session.id)
|
|
376
|
+
// Spread the downstream decision so its own fields survive; the only field this
|
|
377
|
+
// listener owns is the series restart it was asked for.
|
|
378
|
+
return { ...decision, startsRequestSeries: true }
|
|
379
|
+
})
|
|
380
|
+
|
|
381
|
+
// A disposed Agent takes its layer and the restriction with it; drop the bookkeeping
|
|
382
|
+
// and lift the restriction defensively, so nothing outlives the Session.
|
|
383
|
+
ctx.on('agent/disposed', ({ agent }) => {
|
|
384
|
+
const id = agent?.session?.id
|
|
385
|
+
if (id === undefined) return
|
|
386
|
+
pendingSeries.delete(id)
|
|
387
|
+
const row = offSessions.get(id)
|
|
388
|
+
if (row === undefined) return
|
|
389
|
+
offSessions.delete(id)
|
|
390
|
+
safely(() => row.dispose())
|
|
391
|
+
safely(() => row.disposeGuard?.())
|
|
392
|
+
})
|
|
393
|
+
|
|
394
|
+
/** True when this Agent has no open turn right now. */
|
|
395
|
+
function turnIsOpen(agent) {
|
|
396
|
+
if (agent.status === 'running') return true
|
|
397
|
+
const boundary = safely(() => ctx.agents.turnBoundaryOf(agent.session))
|
|
398
|
+
return boundary !== undefined && boundary.openTurnStartSeq !== null
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Whether the web tools are denied for the Agent in front of us. A row left behind
|
|
403
|
+
* by an earlier Agent of the same Session does not count: the restriction lives on
|
|
404
|
+
* that Agent's scope, so a re-created Agent starts with the tools visible.
|
|
405
|
+
* @param agent - the Agent whose state is asked for.
|
|
406
|
+
* @returns true when this exact Agent is restricted.
|
|
407
|
+
*/
|
|
408
|
+
function isOff(agent) {
|
|
409
|
+
const row = offSessions.get(agent.session.id)
|
|
410
|
+
return row !== undefined && row.agent === agent
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Build the command result for one state.
|
|
415
|
+
* @param agent - the Agent whose state is reported.
|
|
416
|
+
* @param changed - whether this call changed the state.
|
|
417
|
+
* @returns the result the UI renders (and the Session log records).
|
|
418
|
+
*/
|
|
419
|
+
function report(agent, changed) {
|
|
420
|
+
const off = isOff(agent)
|
|
421
|
+
const marker = markerOf(off)
|
|
422
|
+
if (off) {
|
|
423
|
+
return {
|
|
424
|
+
kind: 'success',
|
|
425
|
+
text: changed
|
|
426
|
+
? `已断网:从下一次请求起,本会话只剩本地工具(shell 保留,但联网类命令会被拦下),网页搜索、浏览器、MCP、生图/视频、子代理全部隐藏。 ${marker} / Network off for this session: local work only, and shell commands that would fetch anything are refused.`
|
|
427
|
+
: `本会话本来就是断网状态,没有重复加限制。 ${marker} / The network was already off for this session.`,
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
return {
|
|
431
|
+
kind: 'success',
|
|
432
|
+
text: changed
|
|
433
|
+
? `已恢复联网:完整工具列表回到本会话。 ${marker} / Network restored for this session.`
|
|
434
|
+
: `本会话本来就是联网状态,没有改动。 ${marker} / The network was already on for this session.`,
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* Hide every network-capable tool for one Agent and arm the request-series rebuild.
|
|
440
|
+
* @param agent - the receiving Agent.
|
|
441
|
+
* @returns the command result the UI renders.
|
|
442
|
+
*/
|
|
443
|
+
function switchOff(agent) {
|
|
444
|
+
const sessionId = agent.session.id
|
|
445
|
+
// The allowlist must only name tools this deployment actually registers: a name
|
|
446
|
+
// that is not in the catalog would make `restrict()` throw instead of narrowing.
|
|
447
|
+
// Read once per toggle — this is the only catalog-sized work the plugin ever does.
|
|
448
|
+
const known = safely(() => ctx.tools.view().restrictableNames)
|
|
449
|
+
const allow = known === undefined ? [] : [...LOCAL_TOOLS, ...GUARDED_TOOLS].filter((name) => known.has(name))
|
|
450
|
+
if (allow.length === 0) {
|
|
451
|
+
return {
|
|
452
|
+
kind: 'error',
|
|
453
|
+
text: '无法断网:本部署没有注册任何可保留的本地工具 / Could not switch off: none of the local tools are registered here.',
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
// Arm BEFORE the restriction lands: if the restriction is resolvable while the
|
|
457
|
+
// mark is missing, a request could describe the old catalog.
|
|
458
|
+
pendingSeries.add(sessionId)
|
|
459
|
+
let dispose
|
|
460
|
+
let disposeGuard
|
|
461
|
+
try {
|
|
462
|
+
// Scope-bound: the restriction applies to this Agent alone, and it fails closed —
|
|
463
|
+
// a tool that is not in the allowlist (including one added later) is hidden.
|
|
464
|
+
dispose = agent.ctx.tools.restrict({ allow })
|
|
465
|
+
// The kept dual-use tools are fenced here rather than hidden.
|
|
466
|
+
disposeGuard = agent.ctx.tools.guard(networkGuard)
|
|
467
|
+
} catch (error) {
|
|
468
|
+
pendingSeries.delete(sessionId)
|
|
469
|
+
if (dispose !== undefined) safely(() => dispose())
|
|
470
|
+
return {
|
|
471
|
+
kind: 'error',
|
|
472
|
+
text: `无法断网 / Could not turn the network off: ${messageOf(error)}`,
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
offSessions.set(sessionId, { agent, dispose, disposeGuard })
|
|
476
|
+
return report(agent, true)
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* Lift the restriction on one Agent and arm the request-series rebuild.
|
|
481
|
+
* @param agent - the receiving Agent.
|
|
482
|
+
* @returns the command result the UI renders.
|
|
483
|
+
*/
|
|
484
|
+
function switchOn(agent) {
|
|
485
|
+
const sessionId = agent.session.id
|
|
486
|
+
const row = offSessions.get(sessionId)
|
|
487
|
+
if (row === undefined || row.agent !== agent) {
|
|
488
|
+
// Nothing of this Agent's is restricted, but a stale row from an earlier Agent
|
|
489
|
+
// of the same Session still owns a disposer: drop it rather than leak it.
|
|
490
|
+
if (row !== undefined) {
|
|
491
|
+
offSessions.delete(sessionId)
|
|
492
|
+
safely(() => row.dispose())
|
|
493
|
+
safely(() => row.disposeGuard?.())
|
|
494
|
+
}
|
|
495
|
+
offSessions.delete(sessionId)
|
|
496
|
+
return report(agent, false)
|
|
497
|
+
}
|
|
498
|
+
offSessions.delete(sessionId)
|
|
499
|
+
try {
|
|
500
|
+
row.dispose()
|
|
501
|
+
if (row.disposeGuard !== undefined) row.disposeGuard()
|
|
502
|
+
} catch (error) {
|
|
503
|
+
// The layer may already be torn down; the state is on either way, but say so.
|
|
504
|
+
return {
|
|
505
|
+
kind: 'error',
|
|
506
|
+
text: `已取消记录,但撤销限制时报告错误 / Recorded as on, but lifting the restriction reported: ${messageOf(error)}`,
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
pendingSeries.add(sessionId)
|
|
510
|
+
return report(agent, true)
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* Switch this Session's web tools on or off.
|
|
515
|
+
* @param agent - the receiving Agent (the Session whose switch is being changed).
|
|
516
|
+
* @param rawInput - `on`, `off`, `status`, or empty to toggle.
|
|
517
|
+
* @returns the command result the UI renders.
|
|
518
|
+
*/
|
|
519
|
+
function toggle(agent, rawInput) {
|
|
520
|
+
if (agent?.session?.id === undefined) {
|
|
521
|
+
return { kind: 'error', text: '没有可切换的会话 / No Session to switch.' }
|
|
522
|
+
}
|
|
523
|
+
const requested = typeof rawInput === 'string' ? (rawInput.trim().toLowerCase().split(/\s+/)[0] ?? '') : ''
|
|
524
|
+
if (requested === 'status') return report(agent, false)
|
|
525
|
+
if (requested !== '' && requested !== 'on' && requested !== 'off') {
|
|
526
|
+
return {
|
|
527
|
+
kind: 'error',
|
|
528
|
+
text: `用法 / usage: /${COMMAND} [on|off|status](不带参数则切换 / no argument toggles)`,
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
const current = isOff(agent)
|
|
532
|
+
const next = requested === '' ? !current : requested === 'off'
|
|
533
|
+
// Idempotent: a second "off" must not stack a second restriction, and a second
|
|
534
|
+
// "on" must not dispose twice.
|
|
535
|
+
if (next === current) return report(agent, false)
|
|
536
|
+
// A turn that is already running has its tool set admitted; changing the catalog
|
|
537
|
+
// mid-turn would either be ignored or split one request from its declarations, so
|
|
538
|
+
// this switch queues nothing and refuses instead.
|
|
539
|
+
if (turnIsOpen(agent)) {
|
|
540
|
+
return {
|
|
541
|
+
kind: 'error',
|
|
542
|
+
text: '当前任务正在执行,等这一轮结束后再切换联网开关 / This task is running; switch the web tools after the turn ends.',
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
return next ? switchOff(agent) : switchOn(agent)
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
ctx.commands.register({
|
|
549
|
+
name: COMMAND,
|
|
550
|
+
description: 'Turn the web tools (web_search / web_fetch) on or off for this Session.',
|
|
551
|
+
input: { hint: 'on|off|status' },
|
|
552
|
+
handler: ({ agent, rawInput }) => toggle(agent, rawInput),
|
|
553
|
+
})
|
|
554
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Network switch",
|
|
4
|
+
"description": "Adds a per-task switch to the composer toolbar: turn it off and this task keeps only local tools, so web search, the browser, MCP servers and the shell can no longer reach the network; turn it on to restore them. Other tasks are unaffected.",
|
|
5
|
+
"detail": "docs/DETAIL.md"
|
|
6
|
+
}
|
|
7
|
+
}
|
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-web-toggle",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"description": "在对话输入框工具栏加一个按会话独立的联网开关:关掉后本会话的模型看不到 web_search / web_fetch,再点一次恢复。",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./index.js",
|
|
9
|
+
"./client": "./client.js",
|
|
10
|
+
"./locale/*.json": "./locale/*.json",
|
|
11
|
+
"./icon": "./icon.svg"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"index.js",
|
|
15
|
+
"client.js",
|
|
16
|
+
"cordis.patch.yml",
|
|
17
|
+
"locale/*.json",
|
|
18
|
+
"docs",
|
|
19
|
+
"icon.svg",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE",
|
|
22
|
+
"tests",
|
|
23
|
+
"scripts"
|
|
24
|
+
],
|
|
25
|
+
"keywords": [
|
|
26
|
+
"dsh-plugin",
|
|
27
|
+
"deepseek-harness",
|
|
28
|
+
"dsh",
|
|
29
|
+
"web-search",
|
|
30
|
+
"web-fetch",
|
|
31
|
+
"tool-restriction",
|
|
32
|
+
"composer",
|
|
33
|
+
"plugin"
|
|
34
|
+
],
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"engines": {
|
|
37
|
+
"dsh": ">=0.2.2-rc.1 <0.3.0"
|
|
38
|
+
},
|
|
39
|
+
"dsh": {
|
|
40
|
+
"bundle": {
|
|
41
|
+
"patch": "./cordis.patch.yml"
|
|
42
|
+
},
|
|
43
|
+
"client": {
|
|
44
|
+
"platform": "web",
|
|
45
|
+
"immediately": true,
|
|
46
|
+
"inject": [
|
|
47
|
+
"@deepseek-ai/dsh-api-remotes",
|
|
48
|
+
"@deepseek-ai/dsh-client-locale",
|
|
49
|
+
"@deepseek-ai/dsh-client-ui-conversation"
|
|
50
|
+
]
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
|
|
3
|
+
import { dirname, join, resolve } from 'node:path'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 把本包的运行期文件同步进 profile 里已安装的那份副本。
|
|
8
|
+
*
|
|
9
|
+
* pnpm 的 `file:` 依赖在这里是**拷贝**而不是软链,所以改完源码不重装时,
|
|
10
|
+
* 这个脚本负责把 index.js / client.js / locale / docs / icon 推过去。
|
|
11
|
+
* 用法:node scripts/sync-to-profile.mjs [profileDir]
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
15
|
+
const packageDir = resolve(here, '..')
|
|
16
|
+
const profileDir = process.argv[2] ?? 'C:/Users/Aluminium/.dsh/profiles/desktop'
|
|
17
|
+
const target = join(profileDir, 'node_modules', 'dsh-web-toggle')
|
|
18
|
+
|
|
19
|
+
assert.ok(existsSync(join(target, 'package.json')), `没有已安装的副本:${target}(先跑 plugin_manager install_bundle)`)
|
|
20
|
+
|
|
21
|
+
const samePackage = JSON.parse(readFileSync(join(target, 'package.json'), 'utf8')).name
|
|
22
|
+
assert.equal(samePackage, 'dsh-web-toggle', '目标目录不是本包,拒绝覆盖')
|
|
23
|
+
|
|
24
|
+
const files = [
|
|
25
|
+
['index.js', 'index.js'],
|
|
26
|
+
['client.js', 'client.js'],
|
|
27
|
+
['cordis.patch.yml', 'cordis.patch.yml'],
|
|
28
|
+
['icon.svg', 'icon.svg'],
|
|
29
|
+
['README.md', 'README.md'],
|
|
30
|
+
['locale/en.json', 'locale/en.json'],
|
|
31
|
+
['locale/zh.json', 'locale/zh.json'],
|
|
32
|
+
['docs/DETAIL.md', 'docs/DETAIL.md'],
|
|
33
|
+
['docs/VERIFY.md', 'docs/VERIFY.md'],
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
for (const [source, destination] of files) {
|
|
37
|
+
const from = join(packageDir, source)
|
|
38
|
+
const to = join(target, destination)
|
|
39
|
+
if (!existsSync(from)) {
|
|
40
|
+
console.log(`skip ${source}(不存在)`)
|
|
41
|
+
continue
|
|
42
|
+
}
|
|
43
|
+
mkdirSync(dirname(to), { recursive: true })
|
|
44
|
+
copyFileSync(from, to)
|
|
45
|
+
const identical = readFileSync(from).equals(readFileSync(to))
|
|
46
|
+
assert.ok(identical, `${destination} 同步后仍不一致`)
|
|
47
|
+
console.log(`ok ${destination}`)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
console.log(`\n已同步到 ${target}\n刷新浏览器(以及必要时重启 DSH)后生效。`)
|