@leiyi-works/dsh-session-tmpdir 0.10.16 → 0.11.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.
Files changed (3) hide show
  1. package/README.md +22 -6
  2. package/index.js +589 -48
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -73,16 +73,16 @@ v0.7 起,这条规则不再只靠 `write`/`edit`/`pwsh`/`bash` 四个工具名
73
73
  3. 用户选长期 + 给路径 → 模型调 `longterm_approve({ path, reason, basis })` 登记:**默认 `mode: 'file'` 只批准这一个文件**;用户明确要"整个目录都行"时才用 `mode: 'dir'`。工作区外路径也能登记(例如鸿蒙的 `Download/<包名>/`),但不能登记磁盘根目录、用户主目录本身或层级过浅的目录;
74
74
  4. 之后 `write`/`edit`、shell 命令、`publish` 交付、python 等代码工具才能**新建**该位置的文件;用户否定 → 模型改用 `task_tmpdir` 写 `_tmp`。**改写已存在文件不需要登记**(`allowOverwrite`)。
75
75
 
76
- 白名单**持久保存**在 `<DSH_HOME>/data/session-tmpdir-approvals.json`:同一会话重启后继续有效;会话被删除的条目由清理任务回收。左侧菜单「临时目录」面板只做展示与「移除」(移除后该文件下次新建会重新走审批),不提供手动添加(添加只能来自对话里的用户同意)。
76
+ 白名单**持久保存**在 `<DSH_HOME>/data/tmpdir-guard/approvals.json`:**按会话生效**——同一会话重启、同一会话换机续用都继续有效;其他会话即使路径相同也不会自动放行;会话被删除的条目由清理任务回收。左侧菜单「临时目录」面板只做展示与「移除」(移除后该文件下次新建会重新走审批),不提供手动添加(添加只能来自对话里的用户同意)。
77
77
 
78
- ## guard 行为边界(v0.9)
78
+ ## guard 行为边界(v0.11)
79
79
 
80
80
  判定顺序:`_tmp` 段(只在**工作区内或系统临时目录**里算临时区)→ 已审批文件/目录 → **已存在文件(改写放行,`allowOverwrite`)** → 白名单;其余按"新建产物"处理:工作区内 → 拒绝并提示先问;工作区外 → 按外部落点处理。
81
81
 
82
82
  | 通道 | 判定方式 | 说明 |
83
83
  |---|---|---|
84
84
  | `write` / `edit` | 完整判定 | 新建工作区根条目、未审批位置、工作区外新文件 → 拒绝;目标已存在 → 放行(改写) |
85
- | `pwsh` / `bash` | 命令文本启发式 | 含创建动词(`New-Item`/`cp`/`mv`/`sed`/`tee`…)、重定向(`>`/`>>`)或 **v0.9 写程序**(`ffmpeg`/`pandoc`/`Export-Csv`/`WriteAllText`/`Start-Process`…)时,扫描命令里的绝对路径(Windows 盘符;HarmonyOS/POSIX `/` 开头,先剥掉 `scheme://` URL);**已存在的路径按改写放行**,不存在且未审批 → 拒绝 |
85
+ | `pwsh` / `bash` | 命令文本启发式 | 含创建动词(`New-Item`/`ni`/`cp`/`mv`/`sed`/`tee`…)、重定向(`>`/`>>`)或 **v0.9 写程序**(`ffmpeg`/`pandoc`/`Export-Csv`/`WriteAllText`/`Start-Process`…)时,扫描命令里的绝对路径(Windows 盘符;HarmonyOS/POSIX `/` 开头,先剥掉 `scheme://` URL);**已存在的路径按改写放行**,不存在且未审批 → 拒绝。v0.11.0 起还会解析**写目标位置**上的简单变量/环境变量/`~`:同一命令里 `$var = '<绝对路径>'`、`$env:USERPROFILE`、`$HOME`、`%USERPROFILE%`、`~/…`(只解析目标位,读源和内容参数不解析) |
86
86
  | `publish` | 复制目标判定 | 只检查 `target`/`destination`/`to`/`output`/`save_path` 等(`source` 是读侧,不拦);目标不存在且未审批 → 拒绝并提示先问用户 |
87
87
  | `present` | 不拦 | 只声明已有文件为交付物,不复制、不落盘 |
88
88
  | `python` / `node` 等 | 静态扫描 | 写信号(`open(...,'w')`、`write_text`、`shutil.copy`、`json.dump`、`Image.save`…)与同语句路径字面量(含 `sub/x.md` 这类相对路径)配对;动态拼路径拦不到(默认边界) |
@@ -92,7 +92,7 @@ v0.7 起,这条规则不再只靠 `write`/`edit`/`pwsh`/`bash` 四个工具名
92
92
 
93
93
  工作区外"天然允许"范围(无需审批,`outsideAllow` 可追加):`<DSH_HOME>`(`~/.dsh`,含插件/密钥/配置)、`~/.cache`、`~/.npm`、`~/.config`、`~/.local/share`、`~/.flova`、系统临时目录;POSIX 设备上另有 `/tmp`、`/var/tmp`、`/dev/shm`、`/run/user`、`/data/local/tmp`、`/storage/emulated/0/Android/data`。`/dev/null`、`NUL`、`$null` 之类伪路径直接放行。
94
94
 
95
- 拦不到(fail-open,**不是安全边界**):变量/动态拼接的路径、脚本内部逻辑、外部程序、GUI 操作、绕过工具的 fs 调用;`warn` 模式只记日志不拦(`guardOutsideWorkspace`/`publishGuard`/`commandGuard` 的 `warn` 在四个通道统一生效)。
95
+ 拦不到(fail-open,**不是安全边界**):运行时才确定的动态拼接(`Join-Path`/`$(…)` 的结果、循环变量、跨语句/跨工具调用传值、脚本内部逻辑)、**被括号包裹的写命令参数**(`(Set-Content -Path $env:… 'x')` 这种少见写法)、多行普通字符串续行以 `#` 开头的内容、含 `://` 且同段有超长连续字母数字的极端输入、外部程序产物、GUI 操作、绕过工具的 fs 调用;**v0.11.0 起,同一命令内的简单赋值、`$env:USERPROFILE`/`$HOME`/`%USERPROFILE%`/`~` 这类常见写法会按写目标解析**(仍只判「新建文件」,已存在文件照旧改写放行);`warn` 模式只记日志不拦(`guardOutsideWorkspace`/`publishGuard`/`commandGuard` 的 `warn` 在四个通道统一生效)。
96
96
 
97
97
  其它:**工作区内**的规则只在会话工作目录 = 已注册工作区根时生效(会话 `cd` 到子目录时不把项目顶层文件当成"工作区根新建条目");**工作区外**的判定不受 cwd 限制,`cd` 到子目录也照拦(v0.7 修复);guard 是**全局**的——队友/子代理/定时任务会话同样受约束。
98
98
 
@@ -245,12 +245,12 @@ v0.9.10 变更(2026-11-16):**面板默认只显示当前机器的白名单
245
245
 
246
246
  v0.9.11 变更(2026-11-16):**修复 0.9.10 客户端语法错误**(`client.js` 少一个括号,面板无法加载)。面板渲染重写为更简单的数组结构(同样的功能:右侧边栏标签页、5 秒自动刷新、当前机器白名单展示/移除、目标不存在标记)。
247
247
 
248
- v0.9.12 变更(2026-11-16):文案澄清——面板**默认只显示当前机器的白名单**(不是“机器隔离”)。界面过滤只是显示策略;白名单判定仍按绝对路径,其他机器同步来的条目如果路径在本机存在,仍然会生效。
248
+ v0.9.12 变更(2026-11-16):文案澄清——面板**默认只显示当前机器的白名单**(不是“机器隔离”)。界面过滤只是显示策略;白名单判定仍按绝对路径,其他机器同步来的条目如果路径在本机存在,仍然会生效。(**v0.11.0 更正**:白名单判定实际按**会话**生效,其他机器的条目只有在**同一个会话**于本机续用时才生效——见 v0.11.0 变更说明。)
249
249
 
250
250
  v0.10.0 变更(2026-11-16):**白名单条目的路径可移植 + 全机队统一展示**(“N 台机器像一个 DSH”)。
251
251
 
252
252
  1. **可移植路径**:home 下的目标在写入时存成 `~/...`(例如 `~/Desktop/x.exe`);读取/匹配/回收时按**当前机器**的 home 展开。工作区等不在 home 下的路径仍存绝对路径(各机一致即可共享)。
253
- 2. **一次批准、多机生效**:A 机批准 `~/Desktop/x.exe` → 同步后 B 机展开成 `C:\Users\<B用户名>\Desktop\x.exe`,同样免审批(前提是该逻辑位置在 B 机也有意义)。
253
+ 2. **一次批准、多机生效**:A 机批准 `~/Desktop/x.exe` → 同步后 B 机展开成 `C:\Users\<B用户名>\Desktop\x.exe`,同样免审批(前提是该逻辑位置在 B 机也有意义)。(**v0.11.0 更正**:仅适用于**同一会话换机续用**;条目按会话生效,不会授权其他会话。)
254
254
  3. **界面去掉机器过滤**:面板显示整份共享白名单(不是“本机专属”);**本机没有的路径**标记「本机无此路径」(可能存在于其他机器),不会因此自动删除;可移植路径额外标「可移植」。
255
255
  4. 旧条目(绝对路径、home 下)在加载时自动归一为 `~/...` 并落盘;墓碑/合并/按机器回收逻辑不变。
256
256
  5. 仍无法自动统一:盘符/工作区路径不同、机器独有路径——这类按各自绝对路径判定。
@@ -331,3 +331,19 @@ v0.10.3 变更(2026-11-16):
331
331
  - 按用户要求把问询卡片里的两个选项顺序对调:第 1 项改为「长期保存」(description 仍是本会话工作目录的真实绝对路径),第 2 项改为「不长期保存」(description 仍是 `task_tmpdir` 返回的临时目录真实绝对路径 + 随会话删除后 N 天清理)。
332
332
  - 选项标签与说明文案本身不动,只调换先后;`compact` 注入的固定问法、`full` 注入的 A/B 两项及其说明、guard 的 5 处拦截提示全部按新顺序改写。
333
333
  - 只改提示文案顺序;guard 判定、审批、清理逻辑未改。
334
+
335
+ ## v0.11.0 变更(2026-11-20):shell 写目标支持简单变量 / 环境变量 / 波浪号
336
+
337
+ 背景:2026-11-20 的《临时目录插件问题报告》实测 `$out = "…\Desktop\START-WEB.cmd"` + `[IO.File]::WriteAllLines($out, …)` 可绕过 guard(旧实现只扫描同一语句段内的字面量路径),同类写法还有 `$d` + `"$d\a.txt"`、`Out-File $d\b.txt`、`Copy-Item .\x $d\y.txt`、`$env:USERPROFILE\Desktop\x` 等。本版只补齐「新建文件落到长期位置」这一项,**不改变任何放行口径**:已存在文件的改写仍放行、`_tmp`/审批目录/DSH home/缓存/系统临时目录仍放行;也**不新增破坏性操作拦截**(按用户要求,插件只为整齐监控新文件的落盘位置,不能影响正常任务)。
338
+
339
+ 1. **简单赋值回溯**:同一命令文本里 `$var = '<绝对路径>'` / `NAME=<绝对路径>` / `set VAR=<绝对路径>` 记入符号表;只收单行、值必须像绝对路径的赋值,内容字符串、here-string、命令替换(`$(…)`)、数组、相对路径都不进表。
340
+ 2. **只解析写目标位置**:`.NET WriteAllText/WriteAllLines/WriteAllBytes/AppendAllText/…` 的第一个参数、`-Path/-LiteralPath/-FilePath/-OutFile/-Destination/…` 参数、`Set-Content/Add-Content/Out-File/tee/mkdir/md/ni` 的首个位置参数、copy 类命令的 destination、重定向目标、`curl -o`/`wget -O`/`Invoke-WebRequest -OutFile`、`ffmpeg` 最后一个参数。读源(`Copy-Item $src …`、`Get-Content $src`)与内容参数(`-Value $content`)不解析,引号内的文本也不算目标——「生成脚本内容里提到桌面路径」不会被误拦。
341
+ 3. **环境变量 / `~` 展开**:`$env:USERPROFILE`、`$HOME`、`%USERPROFILE%`、`~/…` 按本机展开后参与判定(只展开白名单内的环境名)。解析不出来的(`Join-Path` 结果、循环变量、跨命令赋值)保持原样放行,仍是 fail-open。
342
+ 4. **顺带修掉一处误报**:`echo x > $log` / `> "$env:TEMP\a.txt"` 以前会把变量原文当成工作区里的相对路径(`<工作区>/$log`)而误拒,现在按真实目标判定(`_tmp`/系统临时目录放行,长期位置照拦)。
343
+ 5. **别名**:`ni`(`New-Item` 的别名)补进创建动词表,与 `mkdir`/`md` 一致。
344
+ 6. **文案更正**:注入说明与 README 里「一次批准、多机生效」的表述不准确——白名单条目按**会话**生效(同一会话重启/换机续用仍有效),其他会话不会因路径相同自动放行;条目文件本身仍跨机同步,供面板展示与合并。
345
+ 7. **嵌入脚本 / 注释 / 引号**:PowerShell here-string(`@"…"@` / `@'…'@`)和 POSIX heredoc(`<<EOF`)的**内容**在分段前被屏蔽(视为数据;起始行的 `@"`/`@'` 两个字符也会被抹掉,避免留下未闭合引号把后续语句吞进字符串;结束行允许 `"@; 后续代码` 并保留后续代码参与判定;未闭合按“其余都是数据”处理,语法错误的命令本来也跑不起来);行注释与 `<# … #>` 块注释在判定前剥掉;语句分段改为**引号感知**(`-Value "a; Set-Content …"` 保持一段),所以生成 `.ps1`/`.cmd`/`.sh` 时内容里的路径、注释里的命令都不会被误当成写目标。
346
+ 8. **只读惯用法不误伤**:`> $null` / `2> $null` 这类动态重定向不再把只读命令拖进字面量扫描(`Test-Path … > $null`、`Get-Content … 2> $null`、`node -e "…" > $null` 均放行,动态重定向目标本身仍照常判定);copy 类的 `-Path`/`-LiteralPath` 一律是读源;`-Value (Get-Content -Path $x)` 里的 `-Path` 也是读;`rg -ni` / `grep -ni` 不再因 `ni` 别名误触发。
347
+ 9. **回归测试**:`test/guard.test.mjs` 110 条(原有字面量行为 + 新拦截 + 不误伤 + 嵌入脚本文本 + 只读惯用法/注释/引号/here-string 后续语句等评审回归);另用 0.10.16 与 0.11.0 对同一批 **76 条真实任务命令**做差分,除预期的严格化/误报修复外判定完全一致(脚本见 `test/diff.test.mjs`)。
348
+ 10. **超长单行命令性能**:旧版在「一行 5 万字符且不含 `://`」的输入上会因 URL 正则回溯耗时约 800ms;现在只在确实出现 `://` 时才做 URL 剥离,同输入 <1ms;40KB here-string 的生成命令也在 2ms 内(判定结果不变)。
349
+
package/index.js CHANGED
@@ -129,15 +129,13 @@ const DEFAULT_COMMAND_GUARD = 'deny'
129
129
  const DEFAULT_PUBLISH_GUARD = 'deny'
130
130
  /** Command text that can create a directory/file; used before scanning for paths (v0.7: POSIX verbs). */
131
131
  const CREATE_VERB_PATTERN =
132
- /\b(?:New-Item|mkdir|md(?=\s)|Copy-Item|Move-Item|Set-Content|Add-Content|Out-File|Expand-Archive|git\s+clone|robocopy|tar|unzip|7z|touch|tee|New-ItemProperty|cp|mv|ln|install|dd|rsync|scp|truncate|sed|perl|python3?|node)\b/i
132
+ /\b(?:New-Item|mkdir|(?<!-)md(?=\s)|(?<!-)ni(?=\s)|Copy-Item|Move-Item|Set-Content|Add-Content|Out-File|Expand-Archive|git\s+clone|robocopy|tar|unzip|7z|touch|tee|New-ItemProperty|cp|mv|ln|install|dd|rsync|scp|truncate|sed|perl|python3?|node)\b/i
133
133
  /**
134
134
  * v0.9.4: download commands only write files when they name an output target.
135
135
  * `Invoke-RestMethod …` / `curl https://…` without `-OutFile`/`-o` are pure reads.
136
136
  */
137
137
  const DOWNLOAD_WRITE_PATTERN =
138
138
  /\bInvoke-(?:WebRequest|RestMethod)\b[^;|&\n]*\s-(?:OutFile|OutFileList)\b|\bcurl\b[^;|&\n]*\s(?:-o|--output|-O)\b|\bwget\b[^;|&\n]*\s(?:-O|--output-document)\b|\bStart-Process\b[^;|&\n]*\s-(?:RedirectStandardOutput|RedirectStandardError)\b/i
139
- /** v0.9.4: judge a script statement by statement, so a read-only segment cannot be misread as a write. */
140
- const COMMAND_SEGMENT_SPLIT = /(?:\r?\n|;|&&|\|\||\|)+/
141
139
  /**
142
140
  * v0.10.1: invoking a code interpreter (`node`, `python`, `perl`, `ruby`) is not itself a
143
141
  * file write. Such a segment is judged by the code static scan (write signals paired with
@@ -146,7 +144,7 @@ const COMMAND_SEGMENT_SPLIT = /(?:\r?\n|;|&&|\|\||\|)+/
146
144
  const INTERPRETER_SEGMENT_PATTERN = /(?:^|[\\/\s"'=$&])(?:node(?:\.exe)?|python3?(?:\.exe)?|perl|ruby)\b/i
147
145
  /** Create verbs excluding the interpreters above (other real write commands in the same segment). */
148
146
  const OTHER_CREATE_VERB_PATTERN =
149
- /\b(?:New-Item|mkdir|md(?=\s)|Copy-Item|Move-Item|Set-Content|Add-Content|Out-File|Expand-Archive|git\s+clone|robocopy|tar|unzip|7z|touch|tee|New-ItemProperty|cp|mv|ln|install|dd|rsync|scp|truncate|sed)\b/i
147
+ /\b(?:New-Item|mkdir|(?<!-)md(?=\s)|(?<!-)ni(?=\s)|Copy-Item|Move-Item|Set-Content|Add-Content|Out-File|Expand-Archive|git\s+clone|robocopy|tar|unzip|7z|touch|tee|New-ItemProperty|cp|mv|ln|install|dd|rsync|scp|truncate|sed)\b/i
150
148
  /**
151
149
  * v0.9.5: copy-like commands read their source arguments — only the destination is a
152
150
  * write target. A missing source must never make the guard blame the destination check.
@@ -171,6 +169,48 @@ const REDIRECT_ALL_PATTERN = new RegExp(REDIRECT_SOURCE, 'g')
171
169
  const WIN_ABS_PATH_PATTERN = /(?<![A-Za-z0-9])([A-Za-z]:[\\/][^\s'"`,;|&)}\]>]+)/g
172
170
  /** POSIX absolute path tokens inside a command string (HarmonyOS/POSIX Hosts). */
173
171
  const POSIX_ABS_PATH_PATTERN = /(?:^|[\s'"`(=])(\/(?!\/)[^\s'"`,;|&)}\]<>]+)/g
172
+ // ── v0.11.0: light data-flow for shell commands ─────────────────────────────
173
+ /**
174
+ * A path held in a variable used to bypass the guard entirely: only literal paths
175
+ * inside the *same* statement segment were scanned, so
176
+ * `$out = "C:\Users\me\Desktop\x.cmd"` + `[IO.File]::WriteAllLines($out, …)` passed.
177
+ * The patterns below let the guard resolve a path assigned in one statement and later
178
+ * used in a write *target position* (first argument of a write API, a path parameter,
179
+ * the destination of a copy, a redirection target), while never treating a read source
180
+ * or a content variable as a write target — ordinary scripts keep working.
181
+ */
182
+ const SIMPLE_ASSIGNMENT =
183
+ /^\s*(?:\$([A-Za-z_][A-Za-z0-9_]*)|set\s+([A-Za-z_][A-Za-z0-9_]*)|([A-Za-z_][A-Za-z0-9_]*))\s*=\s*([\s\S]*)$/
184
+ /** First argument of a .NET write API (`[IO.File]::WriteAllLines($out, …)`). */
185
+ const WRITE_API_FIRST_ARG =
186
+ /\b(?:WriteAllText|WriteAllBytes|WriteAllLines|AppendAllText|AppendAllBytes|AppendAllLines|CreateText|OpenWrite)\s*\(\s*\(*\s*([^,()\r\n]+)/gi
187
+ /** Explicit write-target parameters (`-Path`, `-LiteralPath`, `-OutFile`, `-Destination`…). */
188
+ const TARGET_PARAM_ARG =
189
+ /-(Path|LiteralPath|FilePath|OutFile|OutFilePath|Destination|DestinationPath|Dest|Target|TargetPath|OutputFile|OutputPath|SavePath|To)\s+(?:"([^"\r\n]*)"|'([^'\r\n]*)'|([^\s;|&"']+))/gi
190
+ /** First positional argument of the path-first write cmdlets. */
191
+ const FIRST_POSITIONAL_TARGET_ARG =
192
+ /\b(?:Set-Content|Add-Content|Out-File|tee|mkdir|md|ni)\s+(?:"([^"\r\n]*)"|'([^'\r\n]*)'|([^\s;|&"'-][^\s;|&"']*))/gi
193
+ /** `New-Item` positional form: the first quoted argument after the cmdlet. */
194
+ const NEW_ITEM_QUOTED_ARG = /\bNew-Item\b[^;|&\r\n]*?(?:"([^"\r\n]*)"|'([^'\r\n]*)')/gi
195
+ /** curl / wget output flags. */
196
+ const CURL_OUTPUT_ARG = /\bcurl\b[^;|&\r\n]*?\s(?:-o|--output)\s+(?:"([^"\r\n]*)"|'([^'\r\n]*)'|([^\s;|&]+))/gi
197
+ const WGET_OUTPUT_ARG = /\bwget\b[^;|&\r\n]*?\s(?:-O|--output-document)\s+(?:"([^"\r\n]*)"|'([^'\r\n]*)'|([^\s;|&]+))/gi
198
+ /** ffmpeg: the last argument is the output file. */
199
+ const FFMPEG_TAIL = /\bffmpeg(?:\.exe)?\b([^;|&\r\n]*)$/i
200
+ /** Values that can be a real path: drive / UNC / root / tilde / env var / `$HOME` anchored. */
201
+ const PATH_VALUE_ANCHOR = /^(?:[A-Za-z]:[\\/]|\\\\|\/|~[\\/]|\$\{?env:|\$HOME\b|%[A-Za-z_][A-Za-z0-9_]*%)/
202
+ /** Only these environment variable names may be expanded into a path. */
203
+ const EXPANDABLE_ENV_NAMES = new Set([
204
+ 'USERPROFILE',
205
+ 'HOME',
206
+ 'HOMEDRIVE',
207
+ 'HOMEPATH',
208
+ 'TEMP',
209
+ 'TMP',
210
+ 'APPDATA',
211
+ 'LOCALAPPDATA',
212
+ 'PUBLIC',
213
+ ])
174
214
  /** v0.8 claim-on-write: relative `<rootDirName>/<dir>` mentions in a shell command. */
175
215
  const TMP_RELATIVE_PATTERN = /(?:^|[\s'"`(=,;|&])(\.{0,2}[\\/]?_tmp[\\/][^\s'"`,;|&)}\]>]+)/g
176
216
  /** v0.8: shell verbs that create a directory (so an exact `<root>/<dir>` target is a folder). */
@@ -347,11 +387,11 @@ export function buildPromptText(cfg) {
347
387
  'After the user agrees, call `longterm_approve` with that file path, then write it; add mode=dir only when the user explicitly wants the whole directory writable.',
348
388
  `If the user declines, says temporary, or the content is scratch: call \`task_tmpdir\` and write under \`${rootDirName}/<会话标题>/\`. Never invent a workspace-root file or folder instead.`,
349
389
  '',
350
- `The write guard denies creating new files outside \`${rootDirName}/\` that this session has not approved: \`write\`/\`edit\`, shell commands (\`pwsh\`/\`bash\`, including \`ffmpeg\`/\`pandoc\`/\`Export-*\` and .NET write APIs), \`publish\` copies, embedded code runtimes and any other tool that declares path arguments. Allowed without approval: \`${rootDirName}/\`, approved files/directories, existing files (overwrite), existing plugin-source trees (${allowRootPatterns.join(', ')}), root files ${allowRootFiles.join(', ') || '(none)'}, DSH's own home, caches and the OS temp directory.`,
390
+ `The write guard denies creating new files outside \`${rootDirName}/\` that this session has not approved: \`write\`/\`edit\`, shell commands (\`pwsh\`/\`bash\`, including paths held in variables, environment variables or \`~\`, \`ffmpeg\`/\`pandoc\`/\`Export-*\` and .NET write APIs), \`publish\` copies, embedded code runtimes and any other tool that declares path arguments. Allowed without approval: \`${rootDirName}/\`, approved files/directories, existing files (overwrite), existing plugin-source trees (${allowRootPatterns.join(', ')}), root files ${allowRootFiles.join(', ') || '(none)'}, DSH's own home, caches and the OS temp directory.`,
351
391
  '',
352
392
  '### Whitelist panel',
353
393
  '',
354
- `Every approval is stored in the **cloud-synced** file \`<DSH_HOME>/data/tmpdir-guard/approvals.json\` (outside cloud-sync's \`data/session-tmpdir-*\` exclusions). The whitelist is shared by all machines: paths under the user's home are stored **portably** (\`~/...\`) and expanded against each machine's home, so one approval also covers the same logical location on the other machines; workspace paths stay absolute (identical path = shared). Entries carry their origin machine and are merged by id (with tombstones for removals); each machine only auto-prunes entries it created, and entries whose target no longer exists are pruned when the panel refreshes (foreign-machine entries are kept unless never seen anywhere for 7 days). The panel lists the whole shared whitelist and marks entries whose expanded path is missing on this machine as 「本机无此路径」.`,
394
+ `Every approval is stored in the **cloud-synced** file \`<DSH_HOME>/data/tmpdir-guard/approvals.json\` (outside cloud-sync's \`data/session-tmpdir-*\` exclusions). Paths under the user's home are stored **portably** (\`~/...\`) and expanded against each machine's home. Entries carry their origin machine and are merged by id (with tombstones for removals); each machine only auto-prunes entries it created, and entries whose target no longer exists are pruned when the panel refreshes (foreign-machine entries are kept unless never seen anywhere for 7 days). The panel lists the whole shared whitelist and marks entries whose expanded path is missing on this machine as 「本机无此路径」. **An approval authorizes only the session that created it** (resuming that same session on another machine keeps it); an identical path approved by a different session does NOT open the guard — this matters when reading the shared panel.`,
355
395
  ].join('\n')
356
396
  }
357
397
 
@@ -599,21 +639,83 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
599
639
  guardOutsideWorkspace,
600
640
  }
601
641
 
642
+ /** Judge one resolved absolute target; returns a denial reason or undefined. */
643
+ function judgeTargetPath(abs) {
644
+ if (isDevicePath(abs)) return undefined
645
+ // v0.8 claim-on-write: report every resolved target so the caller can attribute
646
+ // unmarked `<rootDirName>/<dir>/` folders to the acting session.
647
+ if (typeof options.onTarget === 'function') {
648
+ try {
649
+ options.onTarget(abs)
650
+ } catch {
651
+ // a reporting callback never changes the verdict
652
+ }
653
+ }
654
+ const verdict = classifyWriteTarget(abs, base, classifyOptions)
655
+ if (verdict.kind === 'allowed' || verdict.kind === 'skip') return undefined
656
+ // v0.9(方案3):已存在的路径 = 改写,放行(重定向目标也一样)。
657
+ if (allowOverwrite && pathExists(abs)) return undefined
658
+ if (verdict.kind === 'outside') {
659
+ if (guardOutsideWorkspace === 'warn') {
660
+ console.info(`[session-task-tmpdir] command guard (warn): ${abs}`)
661
+ return undefined
662
+ }
663
+ return outsideWriteDenialReason(abs, { rootDirName, action: '执行这条命令' })
664
+ }
665
+ // inside the workspace but not approved / not scratch
666
+ if (skipInside) return undefined
667
+ const first = firstSegmentUnder(base, abs)
668
+ if (samePath(dirname(abs), base)) {
669
+ return (
670
+ `命令会新建工作区根目录条目「${basename(abs)}」(${abs})。若需要长期保存:先用 ask_user_question 征求用户意见(固定问法:A「长期保存」/ B「不长期保存」,其它位置让用户写在输入框),` +
671
+ `同意后 longterm_approve 登记目录再执行;临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
672
+ )
673
+ }
674
+ return (
675
+ `命令会新建工作区里的「${first || basename(abs)}」(${abs}),它不在本次会话已批准的长期落点里。` +
676
+ `若需要长期保存:先用 ask_user_question 征求用户意见(固定问法:A「长期保存」/ B「不长期保存」,其它位置让用户写在输入框),同意后 longterm_approve 登记目录再执行;` +
677
+ `临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
678
+ )
679
+ }
680
+
602
681
  /** Judge one statement segment (`;` / `&&` / `||` / `|` / newline separated). */
603
- function judgeSegment(segment) {
682
+ function judgeSegment(segment, symbols) {
604
683
  // v0.7 (review M2): every redirect target counts, not only the first, and `>>` is
605
684
  // parsed as one token instead of leaving a second `>` behind. Quoted text such as
606
685
  // `Write-Host "1 > 0"` and device names (`NUL`, `$null`) are not real targets.
686
+ const quoteRanges = quotedRanges(segment)
607
687
  const redirectTokens = new Set()
688
+ const dynamicRedirectTokens = []
608
689
  for (const match of segment.matchAll(REDIRECT_ALL_PATTERN)) {
609
690
  const token = match[1] ?? match[2] ?? match[3]
610
691
  if (!token) continue
611
692
  const cleaned = token.replace(/["'`]+$/, '')
612
693
  if (!cleaned || /^>+$/.test(cleaned)) continue
694
+ // v0.11.0: `> $log` / `> $d\out.txt` is resolved through the assigned value; the
695
+ // raw text must not be resolved against the workspace cwd (it always looked like
696
+ // `<workspace>/$log`, which produced a bogus "workspace root entry" denial).
697
+ const dynamic =
698
+ match[2] === undefined && isDynamicPathToken(cleaned) && !indexInsideRanges(match.index, quoteRanges)
699
+ // Dynamic redirects never count as `hasRedirect`: `… > $null` / `2> $null` are the
700
+ // usual "silence output" idiom of read-only commands and must not drag the segment
701
+ // into the literal scan (they are judged separately, and `$null` resolves to none).
702
+ if (dynamic) {
703
+ dynamicRedirectTokens.push(token)
704
+ continue
705
+ }
613
706
  if (!looksLikePathValue(cleaned) && !FILE_EXTENSION_PATTERN.test(cleaned)) continue
614
707
  redirectTokens.add(token)
615
708
  }
616
709
  const hasRedirect = redirectTokens.size > 0
710
+ /** v0.11.0: dynamic redirection targets are writes even in read-only statements. */
711
+ const judgeDynamicRedirects = () => {
712
+ if (dynamicRedirectTokens.length === 0) return undefined
713
+ for (const abs of dynamicWriteTargets(segment, symbols, { platform, dynamicRedirectTokens, quoteRanges })) {
714
+ const reason = judgeTargetPath(abs)
715
+ if (reason) return reason
716
+ }
717
+ return undefined
718
+ }
617
719
  // v0.10.1:只调用解释器(node/python/perl/ruby)的段落用“代码静态扫描”判定,
618
720
  // 不把命令文本里的任意绝对路径当成写目标(否则字符串里的示例路径会误伤)。
619
721
  if (
@@ -623,6 +725,8 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
623
725
  !WRITE_PROGRAM_PATTERN.test(segment) &&
624
726
  !DOWNLOAD_WRITE_PATTERN.test(segment)
625
727
  ) {
728
+ const redirectReason = judgeDynamicRedirects()
729
+ if (redirectReason) return redirectReason
626
730
  return codeToolGuardReason(segment, base, {
627
731
  ...classifyOptions,
628
732
  guardOutsideWorkspace,
@@ -635,12 +739,15 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
635
739
  !WRITE_PROGRAM_PATTERN.test(segment) &&
636
740
  !DOWNLOAD_WRITE_PATTERN.test(segment)
637
741
  ) {
638
- // v0.9.4: a read-only statement (e.g. `Test-Path C:\missing`) is never judged.
639
- return undefined
742
+ // v0.9.4: a read-only statement (e.g. `Test-Path C:\missing`) is never judged,
743
+ // except for a dynamic redirection target (`Test-Path $p > $log`).
744
+ return judgeDynamicRedirects()
640
745
  }
641
746
  // v0.7 (review M3): strip `scheme://…` first — `https://` contains `s:/`, which the
642
- // Windows drive-path pattern would otherwise treat as a directory.
643
- const scanText = segment.replace(URL_PATTERN, ' ')
747
+ // Windows drive-path pattern would otherwise treat as a directory. v0.11.0: only run
748
+ // the replace when a URL scheme is actually present (the URL regex backtracks badly
749
+ // on a very long single-line argument without `://`).
750
+ const scanText = segment.includes('://') ? segment.replace(URL_PATTERN, ' ') : segment
644
751
  const ordered = []
645
752
  for (const match of scanText.matchAll(pathPattern)) ordered.push(match[1])
646
753
  const tokens = new Set([...redirectTokens, ...ordered])
@@ -670,54 +777,488 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
670
777
  } catch {
671
778
  continue
672
779
  }
673
- if (isDevicePath(abs)) continue
674
- // v0.8 claim-on-write: report every resolved target so the caller can attribute
675
- // unmarked `<rootDirName>/<dir>/` folders to the acting session.
676
- if (typeof options.onTarget === 'function') {
677
- try {
678
- options.onTarget(abs)
679
- } catch {
680
- // a reporting callback never changes the verdict
780
+ const reason = judgeTargetPath(abs)
781
+ if (reason) return reason
782
+ }
783
+ // v0.11.0: variable / environment / `~` paths in write-target positions. Only target
784
+ // positions are resolved, so read sources and content strings are never blamed.
785
+ for (const abs of dynamicWriteTargets(segment, symbols, { platform, dynamicRedirectTokens, quoteRanges })) {
786
+ const reason = judgeTargetPath(abs)
787
+ if (reason) return reason
788
+ }
789
+ return undefined
790
+ }
791
+
792
+ // v0.11.0: embedded script text is data (blanked), comments are not statements, and
793
+ // splitting is quote-aware so quoted content keeps its `;`/`|` characters intact.
794
+ const commandText = stripComments(blankEmbeddedScripts(String(command)))
795
+ const segments = splitCommandSegments(commandText)
796
+ // v0.11.0: paths assigned in earlier statements of the same command (best effort).
797
+ const symbols = new Map()
798
+ for (const segment of segments) {
799
+ const reason = judgeSegment(segment, symbols)
800
+ if (reason) return reason
801
+ collectPathAssignment(segment, symbols, platform)
802
+ }
803
+ return undefined
804
+ }
805
+
806
+ // ── v0.11.0: helpers for the light shell data-flow ──────────────────────────
807
+
808
+ /**
809
+ * Blank the *content* of embedded scripts (PowerShell here-strings `@"…"@` / `@'…'@`
810
+ * and POSIX heredocs `<<EOF`) before statement segmentation. Models generate
811
+ * `.ps1`/`.cmd`/`.sh` files this way; their content is data, not commands of this
812
+ * invocation, so a path or `$var = '…'` line inside it must never be judged as a write.
813
+ * The opening line keeps its prefix (the real command) and code that follows the
814
+ * closing delimiter is kept too; only the data lines are blanked. Newlines are
815
+ * preserved so line-accurate segmentation still works. An unclosed block is treated as
816
+ * "everything after it is data" — such a command cannot run anyway (syntax error).
817
+ */
818
+ function blankEmbeddedScripts(command) {
819
+ const text = String(command ?? '')
820
+ if (!text.includes('@"') && !text.includes("@'") && !text.includes('<<')) return text
821
+ const lines = text.split('\n')
822
+ const out = []
823
+ const blank = (line) => line.replace(/[^\r]/g, ' ')
824
+ /** Odd number of quotes before `end` means the `@`/`<<` sits inside a quoted string. */
825
+ const quoteParity = (line, end) => {
826
+ let count = 0
827
+ for (let i = 0; i < end; i += 1) {
828
+ const ch = line[i]
829
+ if (ch === '`') {
830
+ i += 1
831
+ continue
832
+ }
833
+ if (ch === '"' || ch === "'") count += 1
834
+ }
835
+ return count % 2
836
+ }
837
+ for (let index = 0; index < lines.length; index += 1) {
838
+ const line = lines[index]
839
+ const bare = line.replace(/\r$/, '')
840
+ // PowerShell here-string opening: `@"` / `@'` ends the line, outside another quote.
841
+ const open = /(?<!["'\w])@(["'])\s*$/.exec(bare)
842
+ if (open && quoteParity(bare, open.index) === 0) {
843
+ const quote = open[1]
844
+ const closePattern = quote === '"' ? /^\s*"\s*@\s*/ : /^\s*'\s*@\s*/
845
+ let closeIndex = -1
846
+ for (let j = index + 1; j < lines.length; j += 1) {
847
+ if (closePattern.test(lines[j].replace(/\r$/, ''))) {
848
+ closeIndex = j
849
+ break
850
+ }
851
+ }
852
+ // Blank the opening `@"` / `@'` as well: keeping it would leave an unterminated
853
+ // quote behind, and every later statement would be swallowed as "quoted text".
854
+ out.push(line.slice(0, open.index) + ' ' + line.slice(open.index + 2))
855
+ if (closeIndex === -1) {
856
+ for (let j = index + 1; j < lines.length; j += 1) out.push(blank(lines[j]))
857
+ index = lines.length
858
+ break
859
+ }
860
+ for (let j = index + 1; j < closeIndex; j += 1) out.push(blank(lines[j]))
861
+ // Keep code that follows the terminator on its line (`"@; Set-Content …`).
862
+ const closeBare = lines[closeIndex]
863
+ const head = closePattern.exec(closeBare.replace(/\r$/, ''))
864
+ out.push(head ? blank(head[0]) + closeBare.slice(head[0].length) : blank(closeBare))
865
+ index = closeIndex
866
+ continue
867
+ }
868
+ // POSIX heredoc opening: `<< EOF` / `<<'EOF'`, outside another quote.
869
+ const heredoc = /(?<!<)<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/.exec(bare)
870
+ if (heredoc && quoteParity(bare, heredoc.index) === 0) {
871
+ const tag = heredoc[2]
872
+ let closeIndex = -1
873
+ for (let j = index + 1; j < lines.length; j += 1) {
874
+ if (lines[j].replace(/\r$/, '').trim() === tag) {
875
+ closeIndex = j
876
+ break
877
+ }
878
+ }
879
+ out.push(line)
880
+ if (closeIndex === -1) {
881
+ for (let j = index + 1; j < lines.length; j += 1) out.push(blank(lines[j]))
882
+ index = lines.length
883
+ break
884
+ }
885
+ for (let j = index + 1; j < closeIndex; j += 1) out.push(blank(lines[j]))
886
+ out.push(blank(lines[closeIndex]))
887
+ index = closeIndex
888
+ continue
889
+ }
890
+ out.push(line)
891
+ }
892
+ return out.join('\n')
893
+ }
894
+
895
+ /**
896
+ * v0.11.0: drop PowerShell/POSIX comments before segmentation. A commented-out command
897
+ * (`# Set-Content -Path $env:APPDATA\x …`) is not a write target; block comments
898
+ * (`<# … #>`) count too. Quoted text is kept; quote state is tracked per line (here-string
899
+ * content is already blanked) and block comments may span lines.
900
+ */
901
+ function stripComments(command) {
902
+ const text = String(command ?? '')
903
+ if (!text.includes('#')) return text
904
+ const out = text.split('')
905
+ let block = false
906
+ for (let i = 0; i < out.length; i += 1) {
907
+ if (out[i] === '\n') continue
908
+ let quote = ''
909
+ let j = i
910
+ while (j < out.length && out[j] !== '\n') {
911
+ const ch = out[j]
912
+ if (block) {
913
+ if (ch === '#' && out[j + 1] === '>') {
914
+ out[j] = ' '
915
+ out[j + 1] = ' '
916
+ j += 2
917
+ block = false
918
+ continue
681
919
  }
920
+ out[j] = ' '
921
+ j += 1
922
+ continue
682
923
  }
683
- const verdict = classifyWriteTarget(abs, base, classifyOptions)
684
- if (verdict.kind === 'allowed' || verdict.kind === 'skip') continue
685
- // v0.9(方案3):已存在的路径 = 改写,放行(重定向目标也一样)。
686
- if (allowOverwrite && pathExists(abs)) continue
687
- if (verdict.kind === 'outside') {
688
- if (guardOutsideWorkspace === 'warn') {
689
- console.info(`[session-task-tmpdir] command guard (warn): ${abs}`)
924
+ if (quote) {
925
+ if (quote === '"' && ch === '`') {
926
+ j += 2
690
927
  continue
691
928
  }
692
- return outsideWriteDenialReason(abs, { rootDirName, action: '执行这条命令' })
929
+ if (ch === quote) quote = ''
930
+ j += 1
931
+ continue
693
932
  }
694
- // inside the workspace but not approved / not scratch
695
- if (skipInside) continue
696
- const first = firstSegmentUnder(base, abs)
697
- if (samePath(dirname(abs), base)) {
698
- return (
699
- `命令会新建工作区根目录条目「${basename(abs)}」(${abs})。若需要长期保存:先用 ask_user_question 征求用户意见(固定问法:A「长期保存」/ B「不长期保存」,其它位置让用户写在输入框),` +
700
- `同意后 longterm_approve 登记目录再执行;临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
701
- )
933
+ if (ch === '"' || ch === "'") {
934
+ quote = ch
935
+ j += 1
936
+ continue
702
937
  }
703
- return (
704
- `命令会新建工作区里的「${first || basename(abs)}」(${abs}),它不在本次会话已批准的长期落点里。` +
705
- `若需要长期保存:先用 ask_user_question 征求用户意见(固定问法:A「长期保存」/ B「不长期保存」,其它位置让用户写在输入框),同意后 longterm_approve 登记目录再执行;` +
706
- `临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
707
- )
938
+ if (ch === '<' && out[j + 1] === '#') {
939
+ out[j] = ' '
940
+ out[j + 1] = ' '
941
+ j += 2
942
+ block = true
943
+ continue
944
+ }
945
+ if (ch === '#') {
946
+ const prev = j > 0 ? out[j - 1] : ' '
947
+ if (!prev || /[\s;|&(){},=]/.test(prev)) {
948
+ while (j < out.length && out[j] !== '\n') {
949
+ out[j] = ' '
950
+ j += 1
951
+ }
952
+ continue
953
+ }
954
+ }
955
+ j += 1
708
956
  }
957
+ i = j - 1
958
+ }
959
+ return out.join('')
960
+ }
961
+
962
+ /**
963
+ * v0.11.0: split a command into statement segments on newline / `;` / `&&` / `||` / `|`
964
+ * **outside quotes**. The old splitter cut quoted content open, so a generated script
965
+ * passed through `-Value "a; Set-Content …"` looked like two real statements.
966
+ */
967
+ function splitCommandSegments(command) {
968
+ const text = String(command ?? '')
969
+ const segments = []
970
+ let start = 0
971
+ let quote = ''
972
+ let i = 0
973
+ const push = (end) => {
974
+ const part = text.slice(start, end).trim()
975
+ if (part) segments.push(part)
976
+ }
977
+ while (i < text.length) {
978
+ const ch = text[i]
979
+ if (quote) {
980
+ if (quote === '"' && ch === '`') {
981
+ i += 2
982
+ continue
983
+ }
984
+ if (ch === quote) {
985
+ if (text[i + 1] === quote) {
986
+ i += 2
987
+ continue
988
+ }
989
+ quote = ''
990
+ }
991
+ i += 1
992
+ continue
993
+ }
994
+ if (ch === '`') {
995
+ i += 2
996
+ continue
997
+ }
998
+ if (ch === '"' || ch === "'") {
999
+ quote = ch
1000
+ i += 1
1001
+ continue
1002
+ }
1003
+ if (ch === '\n' || ch === ';') {
1004
+ push(i)
1005
+ i += 1
1006
+ start = i
1007
+ continue
1008
+ }
1009
+ if (ch === '&' && text[i + 1] === '&') {
1010
+ push(i)
1011
+ i += 2
1012
+ start = i
1013
+ continue
1014
+ }
1015
+ if (ch === '|') {
1016
+ push(i)
1017
+ i += text[i + 1] === '|' ? 2 : 1
1018
+ start = i
1019
+ continue
1020
+ }
1021
+ i += 1
1022
+ }
1023
+ push(text.length)
1024
+ return segments
1025
+ }
1026
+
1027
+ /**
1028
+ * Parenthesis depth for every character of a segment (quotes ignored), so a read-only
1029
+ * `-Path` inside `-Value (Get-Content -Path $x)` is not blamed as a write target.
1030
+ */
1031
+ function parenDepthMap(text, quoteRanges) {
1032
+ const depth = new Int32Array(text.length + 1)
1033
+ let current = 0
1034
+ for (let i = 0; i < text.length; i += 1) {
1035
+ depth[i] = current
1036
+ if (indexInsideRanges(i, quoteRanges)) continue
1037
+ const ch = text[i]
1038
+ if (ch === '(') current += 1
1039
+ else if (ch === ')') current = Math.max(0, current - 1)
1040
+ }
1041
+ depth[text.length] = current
1042
+ return depth
1043
+ }
1044
+
1045
+ /** True for tokens that must be resolved (variables, environment markers, `~`). */
1046
+ function isDynamicPathToken(text) {
1047
+ const value = String(text ?? '')
1048
+ return /[$%]/.test(value) || /^~(?:[\\/]|$)/.test(value)
1049
+ }
1050
+
1051
+ /** Only well-known environment names expand; anything else stays unresolved. */
1052
+ function envPathValue(name) {
1053
+ const key = String(name ?? '').toUpperCase()
1054
+ if (!EXPANDABLE_ENV_NAMES.has(key)) return undefined
1055
+ const value = process.env[key] ?? (key === 'HOME' ? homedir() : undefined)
1056
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined
1057
+ }
1058
+
1059
+ /**
1060
+ * Quoted ranges inside one segment, so a `-Path`/write-API mention that only exists
1061
+ * inside a content string (`-Value "… -Path $x …"`) is never read as a real target.
1062
+ */
1063
+ function quotedRanges(text) {
1064
+ const ranges = []
1065
+ let i = 0
1066
+ while (i < text.length) {
1067
+ const quote = text[i]
1068
+ if (quote !== '"' && quote !== "'") {
1069
+ i += 1
1070
+ continue
1071
+ }
1072
+ const start = i
1073
+ i += 1
1074
+ while (i < text.length) {
1075
+ if (text[i] === '`') {
1076
+ i += 2
1077
+ continue
1078
+ }
1079
+ if (quote === '"' && text[i] === '"' && text[i + 1] === '"') {
1080
+ i += 2
1081
+ continue
1082
+ }
1083
+ if (text[i] === quote) break
1084
+ i += 1
1085
+ }
1086
+ ranges.push([start, Math.min(i + 1, text.length)])
1087
+ i += 1
1088
+ }
1089
+ return ranges
1090
+ }
1091
+
1092
+ /** True when `index` falls inside one of the quoted ranges. */
1093
+ function indexInsideRanges(index, ranges) {
1094
+ for (const [start, end] of ranges) {
1095
+ if (index >= start && index < end) return true
1096
+ }
1097
+ return false
1098
+ }
1099
+
1100
+ /**
1101
+ * Resolve one path expression to an absolute path. Returns undefined when the token is
1102
+ * not a path or still contains something the guard cannot resolve; such a token is left
1103
+ * to the old literal scan instead of being guessed.
1104
+ */
1105
+ function resolveDynamicPathExpression(raw, symbols, platform) {
1106
+ let text = String(raw ?? '').trim()
1107
+ if (!text || text.length > 1024) return undefined
1108
+ if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) text = text.slice(1, -1)
1109
+ if (!text || /[\r\n`]/.test(text) || text.includes('$(')) return undefined
1110
+ // 1) variables assigned earlier in the same command text
1111
+ text = text.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (whole, braced, plain) => {
1112
+ const value = symbols.get(braced ?? plain)
1113
+ return value === undefined ? whole : value
1114
+ })
1115
+ // 2) well-known environment variables, `$HOME` and `~`
1116
+ text = text.replace(/\$\{env:([A-Za-z_][A-Za-z0-9_]*)\}/gi, (whole, name) => envPathValue(name) ?? whole)
1117
+ text = text.replace(/\$env:([A-Za-z_][A-Za-z0-9_]*)/gi, (whole, name) => envPathValue(name) ?? whole)
1118
+ text = text.replace(/%([A-Za-z_][A-Za-z0-9_]*)%/g, (whole, name) => envPathValue(name) ?? whole)
1119
+ if (/\$HOME\b/.test(text)) text = text.replace(/\$HOME\b/g, homedir())
1120
+ text = expandTildePath(text)
1121
+ if (!text || /[$%]/.test(text) || /[*?]/.test(text)) return undefined
1122
+ const absolute =
1123
+ platform === 'win32' ? /^(?:[A-Za-z]:[\\/]|\\\\|\/)/.test(text) : /^[A-Za-z]:[\\/]/.test(text) || /^\//.test(text)
1124
+ if (!absolute) return undefined
1125
+ try {
1126
+ return resolve(text)
1127
+ } catch {
709
1128
  return undefined
710
1129
  }
1130
+ }
711
1131
 
712
- const segments = String(command)
713
- .split(COMMAND_SEGMENT_SPLIT)
714
- .map((part) => part.trim())
715
- .filter(Boolean)
716
- for (const segment of segments) {
717
- const reason = judgeSegment(segment)
718
- if (reason) return reason
1132
+ /**
1133
+ * Record `$var = '<path>'` / `NAME=<path>` / `set VAR=<path>` for later statements.
1134
+ * Only a single-line value that already looks like an absolute path is kept, so content
1135
+ * strings, here-strings, command substitutions and relative paths never enter the map.
1136
+ */
1137
+ function collectPathAssignment(segment, symbols, platform = process.platform) {
1138
+ if (symbols.size >= 500) return
1139
+ const match = SIMPLE_ASSIGNMENT.exec(String(segment ?? ''))
1140
+ if (!match) return
1141
+ const name = match[1] ?? match[2] ?? match[3]
1142
+ if (!name) return
1143
+ // `NAME=value` is an assignment only in POSIX shells; `set NAME=value` only in cmd.exe.
1144
+ // PowerShell (the Windows shell channel) has neither form, so do not poison the map.
1145
+ if (match[3] !== undefined && platform === 'win32') return
1146
+ if (match[2] !== undefined && platform !== 'win32') return
1147
+ let raw = String(match[4] ?? '').trim()
1148
+ // strip an optional trailing brace from `if (x) { $p = '…' }`
1149
+ if (raw.endsWith('}')) raw = raw.slice(0, -1).trim()
1150
+ let singleQuoted = false
1151
+ if (raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')) {
1152
+ raw = raw.slice(1, -1)
1153
+ } else if (raw.length >= 2 && raw.startsWith("'") && raw.endsWith("'")) {
1154
+ raw = raw.slice(1, -1)
1155
+ singleQuoted = true
1156
+ }
1157
+ if (!raw || raw.length > 1024) return
1158
+ if (/[\r\n`]/.test(raw) || raw.includes('$(')) return
1159
+ if (/[;,|]/.test(raw)) return
1160
+ if (/[*?]/.test(raw)) return
1161
+ if (singleQuoted && /[$%]/.test(raw)) return
1162
+ if (!PATH_VALUE_ANCHOR.test(raw) || !/[\\/]/.test(raw)) return
1163
+ symbols.set(name, raw)
1164
+ }
1165
+
1166
+ /**
1167
+ * Index of the first write signal in a segment (`-1` when the segment only reads).
1168
+ * v0.11.0: a read-only `-Path` (e.g. `Test-Path -Path $p`) that appears *before* the
1169
+ * actual write command in the same segment must not be blamed as a write target.
1170
+ */
1171
+ function firstWriteSignalIndex(segment) {
1172
+ let best = -1
1173
+ for (const pattern of [CREATE_VERB_PATTERN, WRITE_PROGRAM_PATTERN, DOWNLOAD_WRITE_PATTERN]) {
1174
+ const match = pattern.exec(segment)
1175
+ if (match && (best === -1 || match.index < best)) best = match.index
719
1176
  }
720
- return undefined
1177
+ return best
1178
+ }
1179
+
1180
+ /** Strip wrapping punctuation around an argument token (`$p)`, `{…}`, `"…"`). */
1181
+ function stripArgEdge(text) {
1182
+ return String(text ?? '')
1183
+ .trim()
1184
+ .replace(/^[([{]+/, '')
1185
+ .replace(/[)\]},]+$/, '')
1186
+ }
1187
+
1188
+ /**
1189
+ * v0.11.0: absolute paths that this segment creates/overwrites but expresses through a
1190
+ * variable, an environment variable or `~`. Only write *target* positions are resolved:
1191
+ * the first argument of a write API, explicit path parameters, the first positional
1192
+ * argument of path-first cmdlets, copy destinations, redirections and download/ffmpeg
1193
+ * outputs. Sources, content arguments and read-only parameters (a `-Path` in front of
1194
+ * the write command) are deliberately ignored.
1195
+ */
1196
+ function dynamicWriteTargets(segment, symbols, options = {}) {
1197
+ const { platform = process.platform, dynamicRedirectTokens = [], quoteRanges = quotedRanges(segment) } = options
1198
+ const found = new Set()
1199
+ const firstWrite = firstWriteSignalIndex(segment)
1200
+ const copyLike = COPY_LIKE_VERB_PATTERN.test(segment)
1201
+ const depthAt = segment.includes('(') ? parenDepthMap(segment, quoteRanges) : undefined
1202
+ /** Resolve a token only when it is dynamic AND not inside quoted content text. */
1203
+ const push = (raw) => {
1204
+ if (raw === undefined || raw === null) return
1205
+ const text = stripArgEdge(raw)
1206
+ if (!text || !isDynamicPathToken(text)) return // literals are handled by the old scan
1207
+ const abs = resolveDynamicPathExpression(text, symbols, platform)
1208
+ if (abs) found.add(abs)
1209
+ }
1210
+ const inTargetRegion = (index) => firstWrite >= 0 && index >= firstWrite && !indexInsideRanges(index, quoteRanges)
1211
+ // A) redirection targets (`> $log`, `4> $d\out.txt`)
1212
+ for (const raw of dynamicRedirectTokens) push(raw)
1213
+ // B) first argument of a .NET write API
1214
+ for (const match of segment.matchAll(WRITE_API_FIRST_ARG)) {
1215
+ if (inTargetRegion(match.index)) push(match[1])
1216
+ }
1217
+ // C) explicit write-target parameters (`-Path`, `-Destination`, `-OutFile`, …)
1218
+ for (const match of segment.matchAll(TARGET_PARAM_ARG)) {
1219
+ if (!inTargetRegion(match.index)) continue
1220
+ // `-Path` / `-LiteralPath` on a copy-like command is the source, never the destination.
1221
+ if (copyLike && /^(?:Path|LiteralPath)$/i.test(match[1])) continue
1222
+ // A read-only `-Path` inside an argument subexpression (`-Value (Get-Content -Path $x)`).
1223
+ if (depthAt && depthAt[match.index] > 0) continue
1224
+ push(match[2] ?? match[4])
1225
+ }
1226
+ // D) first positional argument of path-first cmdlets
1227
+ for (const match of segment.matchAll(FIRST_POSITIONAL_TARGET_ARG)) {
1228
+ if (inTargetRegion(match.index)) push(match[1] ?? match[3])
1229
+ }
1230
+ // E) `New-Item` positional form
1231
+ for (const match of segment.matchAll(NEW_ITEM_QUOTED_ARG)) {
1232
+ if (inTargetRegion(match.index)) push(match[1])
1233
+ }
1234
+ // F) curl / wget output flags
1235
+ for (const match of segment.matchAll(CURL_OUTPUT_ARG)) {
1236
+ if (inTargetRegion(match.index)) push(match[1] ?? match[3])
1237
+ }
1238
+ for (const match of segment.matchAll(WGET_OUTPUT_ARG)) {
1239
+ if (inTargetRegion(match.index)) push(match[1] ?? match[3])
1240
+ }
1241
+ // G) ffmpeg output = last argument of the ffmpeg invocation
1242
+ const ffmpeg = FFMPEG_TAIL.exec(segment)
1243
+ if (ffmpeg && inTargetRegion(ffmpeg.index)) {
1244
+ const args = ffmpeg[1].trim().match(/(?:"[^"]*"|'[^']*'|\S+)/g) ?? []
1245
+ const last = args.map(stripArgEdge).filter((token) => token && !/^[()[\]{}]+$/.test(token)).pop()
1246
+ push(last)
1247
+ }
1248
+ // H) positional destination of a copy-like command (`-Destination` is covered above)
1249
+ if (!DESTINATION_FLAG_PATTERN.test(segment)) {
1250
+ const copy = COPY_LIKE_VERB_PATTERN.exec(segment)
1251
+ if (copy && inTargetRegion(copy.index)) {
1252
+ const tail = segment.slice(copy.index)
1253
+ const args = tail.match(/(?:"[^"]*"|'[^']*'|\S+)/g) ?? []
1254
+ const last = [...args]
1255
+ .reverse()
1256
+ .map(stripArgEdge)
1257
+ .find((token) => token && !token.startsWith('-') && !/^[()[\]{}]+$/.test(token))
1258
+ push(last)
1259
+ }
1260
+ }
1261
+ return [...found]
721
1262
  }
722
1263
 
723
1264
  // ── v0.7: write-channel resolution (capability based, not a fixed tool list) ──
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leiyi-works/dsh-session-tmpdir",
3
- "version": "0.10.16",
3
+ "version": "0.11.0",
4
4
  "type": "module",
5
5
  "description": "Per-session task temp folder with a long-term write guard. v0.9 (方案3): creating a new file outside _tmp requires the user's approval (per file by default, per directory with mode=dir), overwriting an existing file is allowed without asking, every write channel is guarded (write/edit, shell including ffmpeg/pandoc/Export-*/IO APIs, publish copies, code runtimes, unknown tools), and the persisted whitelist is shown in a left-sidebar panel「临时目录」 where entries can be removed. Every session also gets _tmp/<session title>/ in its working directory, cleaned 7 days after the session is deleted; the same tick reclaims the attachment store.",
6
6
  "exports": {