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/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
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "联网开关",
4
+ "description": "在对话输入框工具栏加一个按任务独立的断网开关:关掉后这个任务只剩本地工具,网页搜索、浏览器、MCP、shell 等能出网的通道全部隐藏;再点一次恢复,其他任务和其他本地功能不受影响。",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "dsh-web-toggle",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "按会话独立的联网开关:关掉后本会话的模型看不到 web_search / web_fetch、浏览器、MCP 等出网工具,shell 里的联网命令也会被拦下。Per-session web switch for DeepSeek Harness.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./index.js",
8
+ "./client": "./client.js",
9
+ "./locale/*.json": "./locale/*.json",
10
+ "./icon": "./icon.svg"
11
+ },
12
+ "files": [
13
+ "index.js",
14
+ "client.js",
15
+ "cordis.patch.yml",
16
+ "locale/*.json",
17
+ "docs",
18
+ "icon.svg",
19
+ "README.md",
20
+ "LICENSE",
21
+ "tests",
22
+ "scripts"
23
+ ],
24
+ "keywords": [
25
+ "dsh-plugin",
26
+ "deepseek-harness",
27
+ "dsh",
28
+ "web-search",
29
+ "web-fetch",
30
+ "tool-restriction",
31
+ "composer",
32
+ "plugin"
33
+ ],
34
+ "license": "MIT",
35
+ "author": "AluminiumRanran",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/AluminiumRanran/dsh-web-toggle.git"
39
+ },
40
+ "homepage": "https://github.com/AluminiumRanran/dsh-web-toggle#readme",
41
+ "bugs": {
42
+ "url": "https://github.com/AluminiumRanran/dsh-web-toggle/issues"
43
+ },
44
+ "engines": {
45
+ "dsh": ">=0.2.2-rc.1 <0.3.0"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public",
49
+ "registry": "https://registry.npmjs.org"
50
+ },
51
+ "dsh": {
52
+ "bundle": {
53
+ "patch": "./cordis.patch.yml"
54
+ },
55
+ "client": {
56
+ "platform": "web",
57
+ "immediately": true,
58
+ "inject": [
59
+ "@deepseek-ai/dsh-api-remotes",
60
+ "@deepseek-ai/dsh-client-locale",
61
+ "@deepseek-ai/dsh-client-ui-conversation"
62
+ ]
63
+ }
64
+ }
65
+ }