@leiyi-works/dsh-session-tmpdir 0.8.0 → 0.9.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/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Task Temp Folder(session-task-tmpdir)v0.8.0
1
+ # Task Temp Folder(session-task-tmpdir)v0.9.0
2
2
 
3
3
  给每个 DSH 会话一个**任务临时目录**,并在**会话被删除 7 天后**自动清掉对应目录:
4
4
 
@@ -8,13 +8,16 @@
8
8
 
9
9
  同时守住工作区根目录:**临时文件只能进 `_tmp/`;长期文件必须用户点头后才能落盘**。
10
10
 
11
+ v0.9 起按「中间产物/长期产物」划分落盘规则(方案 3):**在 `_tmp` 之外新建文件 → 先问用户(文件级审批,`mode=dir` 可批整个目录);改写已存在的文件 → 直接放行**。白名单持久保存,并在左侧菜单「临时目录」面板里展示、可移除。
12
+
11
13
  v0.7 起,这条规则不再只靠 `write`/`edit`/`pwsh`/`bash` 四个工具名:**publish 交付复制、python/node 等代码执行工具、以及任何在 schema 里声明了路径参数的写类工具都会被纳入检查**,工作区之外的落点也一并纳入。
12
14
 
13
- ## 一句话规则(v0.7)
15
+ ## 一句话规则(v0.9)
14
16
 
15
- - 临时产物(下载文件、中间数据、截图、调试日志、一次性稿)→ `_tmp/<会话标题>/`,**不问用户**,直接写;
16
- - 长期产物(跨会话复用/存档/交付成品)→ 先问用户(选择题);用户同意 → `longterm_approve` 登记其指定目录后写入;用户否定 → **退回 `_tmp`**;
17
- - 未经同意的长期落点(包括在工作区根新建文件夹、`publish` 到 `Download/`、python 写盘、工作区外任意位置)→ 在**工具层直接拒绝**,并给出纠正提示。
17
+ - 中间产物(下载文件、中间数据、截图、调试日志、一次性稿)→ `_tmp/<会话标题>/`,**不问用户**,直接写;
18
+ - 长期产物(跨会话复用/存档/交付成品)→ **新建文件前**先问用户(选择题);用户同意 → `longterm_approve` 默认按**单个文件**登记(`mode: 'dir'` 才登记整个目录)后写入;用户否定 → **退回 `_tmp`**;
19
+ - **改写已存在的文件**(含覆盖/追加/原地重算)→ 视为改写,**直接放行**,不弹窗(`allowOverwrite: false` 可改回"改写也要审批");
20
+ - 未经同意的**新建**落点(包括在工作区根新建条目、`publish` 到未登记目录、`ffmpeg`/`pandoc` 等程序写盘、python 写盘、工作区外任意新文件)→ 在**工具层直接拒绝**,并给出纠正提示。
18
21
 
19
22
  ## 功能介绍
20
23
 
@@ -44,6 +47,7 @@ v0.7 起,这条规则不再只靠 `write`/`edit`/`pwsh`/`bash` 四个工具名
44
47
  | `cleanupDryRun` | `false` | 只打印"会标记/会删哪些"、不动手 |
45
48
  | `guardWorkspaceRoot` | `true` | v1 临时文件规则总开关(根目录临时命名、`_tmp/` 根文件) |
46
49
  | `requireApprovalOutsideTmp` | `true` | 长期落点审批总开关(`false` 时 v0.5 + v0.7 全部通道的落点判定一并关闭,只留 v1 临时文件规则) |
50
+ | `allowOverwrite` | `true` | **v0.9(方案3)**:已存在的文件视为"改写",直接放行;`false` = 改写也要审批 |
47
51
  | `allowRootPatterns` | `['dsh-*']` | 无需审批的根目录名(glob,`*`/`?`) |
48
52
  | `allowRootFiles` | `['.dsh-standing-rules.md']` | 无需审批的工作区根文件 |
49
53
  | `commandGuard` | `deny` | pwsh/bash 命令守卫:`deny` / `warn`(只记日志)/ `off` |
@@ -65,23 +69,23 @@ v0.7 起,这条规则不再只靠 `write`/`edit`/`pwsh`/`bash` 四个工具名
65
69
 
66
70
  1. 模型判断某文件需要长期保存,且不在任务指定位置;
67
71
  2. 模型调用 `ask_user_question` 给用户选择题(标签只写 **A 不长期保存** / **B 工作区根目录保存**,细节放选项 description 小字;选 B 时模型自行起目录名、不再跟用户确认;其他位置由用户直接在输入框里写路径);
68
- 3. 用户选长期 + 给路径 → 模型调 `longterm_approve({ path, reason, basis })` 登记(**工作区外目录也能登记**,例如鸿蒙的 `Download/<包名>/`;但不能登记磁盘根目录、用户主目录本身或层级过浅的目录);
69
- 4. 之后 `write`/`edit`、shell 命令、`publish` 交付、python 等代码工具才能写该目录;用户否定 → 模型改用 `task_tmpdir` 写 `_tmp`。
72
+ 3. 用户选长期 + 给路径 → 模型调 `longterm_approve({ path, reason, basis })` 登记:**默认 `mode: 'file'` 只批准这一个文件**;用户明确要"整个目录都行"时才用 `mode: 'dir'`。工作区外路径也能登记(例如鸿蒙的 `Download/<包名>/`),但不能登记磁盘根目录、用户主目录本身或层级过浅的目录;
73
+ 4. 之后 `write`/`edit`、shell 命令、`publish` 交付、python 等代码工具才能**新建**该位置的文件;用户否定 → 模型改用 `task_tmpdir` 写 `_tmp`。**改写已存在文件不需要登记**(`allowOverwrite`)。
70
74
 
71
- `longterm_approve` 的登记是**按会话内存保存**:Host 重启或会话结束即清空,需要时重新审批(不会把"同意"永久写死)。
75
+ 白名单**持久保存**在 `<DSH_HOME>/data/session-tmpdir-approvals.json`:同一会话重启后继续有效;会话被删除的条目由清理任务回收。左侧菜单「临时目录」面板只做展示与「移除」(移除后该文件下次新建会重新走审批),不提供手动添加(添加只能来自对话里的用户同意)。
72
76
 
73
- ## guard 行为边界(v0.7)
77
+ ## guard 行为边界(v0.9)
74
78
 
75
- 判定顺序:`_tmp` 段(只在**工作区内或系统临时目录**里算临时区,v0.7 收紧)→ 已登记目录 → 白名单;工作区内走长期落点判定,工作区外走外部落点判定。
79
+ 判定顺序:`_tmp` 段(只在**工作区内或系统临时目录**里算临时区)→ 已审批文件/目录 → **已存在文件(改写放行,`allowOverwrite`)** → 白名单;其余按"新建产物"处理:工作区内 → 拒绝并提示先问;工作区外 → 按外部落点处理。
76
80
 
77
81
  | 通道 | 判定方式 | 说明 |
78
82
  |---|---|---|
79
- | `write` / `edit` | 完整判定 | 工作区根新建、未登记子目录、工作区外未登记 → 拒绝 |
80
- | `pwsh` / `bash` | 命令文本启发式 | 含创建动词(`New-Item`/`cp`/`mv`/`sed`/`tee`…)或重定向(`>`/`>>`)时,扫描命令里的绝对路径(Windows 盘符;HarmonyOS/POSIX `/` 开头,先剥掉 `scheme://` URL);重定向目标即使已存在也判(覆盖/追加属长期写入),其它已存在路径不拦(多为 copy/读取源) |
81
- | `publish` | 复制目标判定 | 只检查 `target`/`destination`/`to`/`output`/`save_path` 等(`source` 是读侧,不拦);目标在工作区根、未登记子目录或工作区外 → 拒绝并提示先问用户 |
83
+ | `write` / `edit` | 完整判定 | 新建工作区根条目、未审批位置、工作区外新文件 → 拒绝;目标已存在 → 放行(改写) |
84
+ | `pwsh` / `bash` | 命令文本启发式 | 含创建动词(`New-Item`/`cp`/`mv`/`sed`/`tee`…)、重定向(`>`/`>>`)或 **v0.9 写程序**(`ffmpeg`/`pandoc`/`Export-Csv`/`WriteAllText`/`Start-Process`…)时,扫描命令里的绝对路径(Windows 盘符;HarmonyOS/POSIX `/` 开头,先剥掉 `scheme://` URL);**已存在的路径按改写放行**,不存在且未审批 → 拒绝 |
85
+ | `publish` | 复制目标判定 | 只检查 `target`/`destination`/`to`/`output`/`save_path` 等(`source` 是读侧,不拦);目标不存在且未审批 → 拒绝并提示先问用户 |
82
86
  | `present` | 不拦 | 只声明已有文件为交付物,不复制、不落盘 |
83
87
  | `python` / `node` 等 | 静态扫描 | 写信号(`open(...,'w')`、`write_text`、`shutil.copy`、`json.dump`、`Image.save`…)与同语句路径字面量(含 `sub/x.md` 这类相对路径)配对;动态拼路径拦不到(默认边界) |
84
- | 其它工具 | schema 兜底 | 工具名/描述含写语义(write/save/export/render/copy/install…)且**顶层**参数值像路径时,**只拦两类高危目标**:工作区根新条目、工作区外未登记位置;工作区内子目录放行,避免误伤 |
88
+ | 其它工具 | schema 兜底 | 工具名/描述含写语义(write/save/export/render/copy/install…)且**顶层**参数值像路径时,**与 `write`/`edit` 同一套规则**(v0.9 去掉了"工作区子目录放行"的例外):已存在 → 放行,新建未审批 → 拒绝 |
85
89
 
86
90
  **不误伤的设计**(v0.7 审查后加固):只读工具名(`read*`/`list*`/`get*`/`show*`/`view*`/`check*`/`status*`/`query*`/`search*`/`find*`/`glob`/`grep`/`count*`/`stat*`)一律跳过;本插件自己的 `task_tmpdir`/`longterm_approve`/`tmp_cleanup` 永远放行;schema 里声明为 `enum` 的参数、`@e3`/`#submit` 这类选择器、`this_session`/`new_once` 这类枚举值、`@scope/pkg` 包名和 URL 都不算路径;嵌套对象里的同名参数(`expect[].target`、workflow `args.files`)不算写目标。
87
91
 
@@ -188,3 +192,14 @@ v0.7.0 变更(2026-11-15):按 HarmonyOS DSHM 真机反馈(桌面文件
188
192
  **独立审查后加固(同发 0.7.0)**:`longterm_approve`/`task_tmpdir`/`tmp_cleanup` 永远不被自己的 guard 判定(否则审批通道自锁);未知工具通道只看顶层参数,跳过 enum、选择器、包名和 URL(否则 `schedule_create`/`bsk_interact`/`plugin_manager` 必被误拒);只读工具名白名单(`read_image` 等);`>>` 重定向正确解析、`NUL`/`$null`/引号内文本不误判、Windows 路径扫描先剥 URL;工作区外 `_tmp` 段不再算临时区;工作区外判定不再随 cwd 关闭;重定向到已存在长期文件仍拒绝;`longterm_approve` 传入不存在的文件路径时登记其目录、并拒绝登记工作区根本身;`toolWritePlan` 判定改用实际参数值,POSIX 大小写/分隔符语义按平台区分。审查时用本机 59 个 live 工具矩阵验证:53 个工具零误伤,仅真实写类工具(`write`/`edit`/`pwsh`)和参数值确实是路径的兜底工具被判定。
189
193
 
190
194
  v0.8.0 变更(2026-11-16):**写入即认领**(claim-on-write)。此前只有 `task_tmpdir` 会写 `.dsh-task.json`;模型若用普通 `write` 或 `pwsh New-Item` 在临时根下自起目录名,目录没有标记,按“手工目录不碰”原则永远不会被清理(本机实测积累 8 个、77 MB)。现在 guard 在**放行后**把写入目标里 `<临时根>/<目录>/…` 的直接子目录补写标记(含当前会话 id 与标题),覆盖 `write`/`edit`、`publish` 复制目标、`python`/`node` 代码里的静态路径、shell 命令的绝对路径与相对 `_tmp/…` 引用、未知写类工具的路径参数;目录不存在时先创建(写入本来就会创建,提前一步无副作用)。**放行/拒绝判定、清理宽限期与既有 marker 格式均未改变**;无标记目录一旦被认领,就按原规则在会话删除 7 天后清理。新增 `tmpClaimDirsForTargets` / `relativeTmpTargets` / `claimTmpDirsSync` 三个导出函数,便于单元测试。
195
+
196
+ v0.9.0 变更(2026-11-16):**中间产物/长期产物划分(方案 3)+ 白名单面板**。
197
+
198
+ 1. **新建才问、改写放行**:`_tmp` 之外**新建文件**必须先经用户同意;目标**已存在**(普通文件)视为改写,直接放行(新配置 `allowOverwrite`,默认 `true`,设为 `false` 可要求改写也审批)。指令重定向、`Set-Content` 覆盖已有文件、`office_recalculate` 原地改写都按这条走。
199
+ 2. **审批粒度改为文件级**:`longterm_approve` 默认 `mode: 'file'`(登记精确文件路径);用户明确要"整个目录都行"时才 `mode: 'dir'`。旧目录登记语义保留。
200
+ 3. **未知工具统一规则**:去掉"工作区子目录放行"的例外,未知写类工具与 `write`/`edit` 判同一套(新建未审批 → 拒绝;已存在 → 放行)。
201
+ 4. **程序级漏网补齐**:`CREATE_VERB_PATTERN` 之外新增 `WRITE_PROGRAM_PATTERN`——`ffmpeg`、`pandoc`、`soffice`/`libreoffice`、`wkhtmltopdf`、`magick`、`convert`、`gs`、`Export-Csv`/`Export-Clixml`/`Export-Pdf`、`[IO.File]::WriteAllText` 系列、`Start-Process` 等都会触发路径扫描,不再整条命令绕过。
202
+ 5. **白名单持久化 + 面板**:新增 `<DSH_HOME>/data/session-tmpdir-approvals.json`(含 sessionId / path / kind / 时间),同一会话重启后继续有效;会话删除的条目由清理任务回收。左侧菜单新增「临时目录」入口,面板表格展示白名单(路径 / 文件或目录 / 同意时间 / 来源会话)并可「移除」;移除后该文件下次新建会重新走审批。
203
+ 6. 宿主接口:`GET /__dsh-session-tmpdir/state`、`POST /__dsh-session-tmpdir/revoke`;新增 `client.js`(左侧菜单 + 面板)与 `dsh.client` 客户端配置。
204
+
205
+ **仍拦不到(fail-open)**:变量/动态拼接路径、脚本内部写盘、GUI/外部程序产物——这部分任何工具层插件都无法保证,只能靠对话规则或后续"工作区巡查"兜底。
package/client.js ADDED
@@ -0,0 +1,244 @@
1
+ /**
2
+ * dsh-session-tmpdir — Client half(v0.9).
3
+ *
4
+ * 左侧菜单「临时目录」+ 全页面板:展示长期落点白名单(文件级/目录级),
5
+ * 支持「移除」一条(让下一次写入重新走审批),不提供手动添加(添加只走对话审批)。
6
+ *
7
+ * 数据来自宿主只读/可写接口:
8
+ * GET /__dsh-session-tmpdir/state 白名单清单 + 配置
9
+ * POST /__dsh-session-tmpdir/revoke { id } 移除一条
10
+ */
11
+ window.__ModuleLoader__.load({
12
+ id: '@leiyi-works/dsh-session-tmpdir',
13
+ factory(require) {
14
+ const React = require('react')
15
+ const h = React.createElement
16
+ const PANEL_ID = 'session-tmpdir'
17
+ const API = '/__dsh-session-tmpdir'
18
+
19
+ const styles = {
20
+ root: {
21
+ height: '100%',
22
+ overflow: 'auto',
23
+ boxSizing: 'border-box',
24
+ padding: 'calc(var(--dsh-frame-top-clearance, 0px) + 16px) 14px 28px',
25
+ color: 'var(--dsw-alias-label-primary)',
26
+ fontSize: 13,
27
+ lineHeight: 1.55,
28
+ },
29
+ inner: { maxWidth: 900, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 10 },
30
+ title: { margin: 0, fontSize: 17, fontWeight: 600 },
31
+ hint: { margin: 0, color: 'var(--dsw-alias-label-secondary)', fontSize: 12 },
32
+ meta: { fontSize: 11, color: 'var(--dsw-alias-label-secondary)' },
33
+ bar: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginTop: 2 },
34
+ btn: {
35
+ appearance: 'none',
36
+ cursor: 'pointer',
37
+ borderRadius: 7,
38
+ padding: '4px 12px',
39
+ fontSize: 12,
40
+ lineHeight: '18px',
41
+ border: '1px solid var(--dsw-alias-border-l2, rgba(127,127,127,.35))',
42
+ background: 'transparent',
43
+ color: 'var(--dsw-alias-label-primary)',
44
+ },
45
+ btnDanger: {
46
+ appearance: 'none',
47
+ cursor: 'pointer',
48
+ borderRadius: 7,
49
+ padding: '3px 10px',
50
+ fontSize: 12,
51
+ lineHeight: '18px',
52
+ border: '1px solid var(--dsw-alias-state-error-primary, #d14a4a)',
53
+ background: 'transparent',
54
+ color: 'var(--dsw-alias-state-error-primary, #d14a4a)',
55
+ whiteSpace: 'nowrap',
56
+ },
57
+ table: { display: 'flex', flexDirection: 'column', gap: 6, marginTop: 4 },
58
+ row: {
59
+ display: 'flex',
60
+ alignItems: 'center',
61
+ gap: 10,
62
+ border: '1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.22))',
63
+ borderRadius: 8,
64
+ padding: '8px 10px',
65
+ },
66
+ rowMain: { flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 3 },
67
+ path: { fontFamily: 'ui-monospace, Consolas, monospace', fontSize: 12, wordBreak: 'break-all' },
68
+ rowMeta: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' },
69
+ tag: {
70
+ fontSize: 10,
71
+ lineHeight: '16px',
72
+ padding: '0 6px',
73
+ borderRadius: 6,
74
+ background: 'var(--dsw-alias-bg-layer-2, rgba(127,127,127,.08))',
75
+ color: 'var(--dsw-alias-label-secondary)',
76
+ },
77
+ empty: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)', margin: '8px 0 0' },
78
+ err: { fontSize: 12, color: 'var(--dsw-alias-state-error-primary, #d14a4a)', margin: 0 },
79
+ }
80
+
81
+ function fmtTime(ms) {
82
+ if (!ms) return ''
83
+ try {
84
+ const d = new Date(ms)
85
+ const pad = (n) => String(n).padStart(2, '0')
86
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
87
+ } catch {
88
+ return ''
89
+ }
90
+ }
91
+
92
+ function shortSession(id) {
93
+ if (typeof id !== 'string' || !id) return ''
94
+ return id.replace(/^session-/, '').slice(0, 8)
95
+ }
96
+
97
+ function WhitelistPanel() {
98
+ const [state, setState] = React.useState({ loading: true, error: '', data: null })
99
+ const [busy, setBusy] = React.useState('')
100
+
101
+ const load = React.useCallback(async () => {
102
+ setState((prev) => ({ ...prev, loading: true, error: '' }))
103
+ try {
104
+ const res = await fetch(`${API}/state`, { cache: 'no-store' })
105
+ const data = await res.json()
106
+ if (!data || data.ok !== true) throw new Error(data?.error || '读取失败')
107
+ setState({ loading: false, error: '', data })
108
+ } catch (error) {
109
+ setState({ loading: false, error: String(error?.message ?? error), data: null })
110
+ }
111
+ }, [])
112
+
113
+ React.useEffect(() => {
114
+ void load()
115
+ }, [load])
116
+
117
+ const remove = async (id) => {
118
+ setBusy(id)
119
+ try {
120
+ const res = await fetch(`${API}/revoke`, {
121
+ method: 'POST',
122
+ headers: { 'content-type': 'application/json' },
123
+ body: JSON.stringify({ id }),
124
+ })
125
+ const data = await res.json()
126
+ if (!data || data.ok !== true) throw new Error(data?.error || '移除失败')
127
+ await load()
128
+ } catch (error) {
129
+ setState((prev) => ({ ...prev, error: String(error?.message ?? error) }))
130
+ } finally {
131
+ setBusy('')
132
+ }
133
+ }
134
+
135
+ const data = state.data
136
+ const rows = (data && Array.isArray(data.approvals) ? data.approvals : []).slice()
137
+
138
+ return h(
139
+ 'div',
140
+ { style: styles.root },
141
+ h(
142
+ 'div',
143
+ { style: styles.inner },
144
+ h('h1', { style: styles.title }, '临时目录'),
145
+ h(
146
+ 'p',
147
+ { style: styles.hint },
148
+ '长期落点白名单:在临时目录外**新建**产物要先经过你同意,同意后才会出现在这里;**改写已存在文件**按规则直接放行,不弹窗。',
149
+ ),
150
+ data
151
+ ? h(
152
+ 'p',
153
+ { style: styles.meta },
154
+ `存储:${data.approvalsFile || ''} · 改写放行:${data.allowOverwrite ? '是' : '否'} · 临时根目录:${data.rootDirName || '_tmp'}/`,
155
+ )
156
+ : null,
157
+ h(
158
+ 'div',
159
+ { style: styles.bar },
160
+ h(
161
+ 'button',
162
+ { style: styles.btn, onClick: () => void load(), disabled: state.loading || Boolean(busy) },
163
+ state.loading ? '读取中…' : '刷新',
164
+ ),
165
+ ),
166
+ state.error ? h('p', { style: styles.err }, state.error) : null,
167
+ rows.length === 0
168
+ ? h('p', { style: styles.empty }, state.loading ? '' : '白名单为空。')
169
+ : h(
170
+ 'div',
171
+ { style: styles.table },
172
+ rows.map((row) =>
173
+ h(
174
+ 'div',
175
+ { key: row.id, style: styles.row },
176
+ h(
177
+ 'div',
178
+ { style: styles.rowMain },
179
+ h('div', { style: styles.path }, row.path),
180
+ h(
181
+ 'div',
182
+ { style: styles.rowMeta },
183
+ h('span', { style: styles.tag }, row.kind === 'dir' ? '目录' : '文件'),
184
+ h('span', { style: styles.meta }, `同意于 ${fmtTime(row.approvedAt) || '未知时间'}`),
185
+ row.sessionId
186
+ ? h(
187
+ 'span',
188
+ { style: styles.meta },
189
+ `会话 ${shortSession(row.sessionId)}${row.current ? '(当前)' : ''}`,
190
+ )
191
+ : null,
192
+ row.reason ? h('span', { style: styles.meta }, row.reason) : null,
193
+ ),
194
+ ),
195
+ h(
196
+ 'button',
197
+ { style: styles.btnDanger, disabled: busy === row.id, onClick: () => void remove(row.id) },
198
+ busy === row.id ? '移除中…' : '移除',
199
+ ),
200
+ ),
201
+ ),
202
+ ),
203
+ ),
204
+ )
205
+ }
206
+
207
+ function TempDirIcon() {
208
+ return h(
209
+ 'span',
210
+ {
211
+ style: {
212
+ width: 18,
213
+ height: 18,
214
+ display: 'inline-flex',
215
+ alignItems: 'center',
216
+ justifyContent: 'center',
217
+ fontSize: 14,
218
+ lineHeight: 1,
219
+ },
220
+ 'aria-hidden': 'true',
221
+ },
222
+ '📁',
223
+ )
224
+ }
225
+
226
+ return {
227
+ name: '@leiyi-works/dsh-session-tmpdir',
228
+ inject: ['slots'],
229
+ apply(ctx) {
230
+ ctx.effect(
231
+ () => ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL_ID }, WhitelistPanel)),
232
+ 'session-task-tmpdir: whitelist page',
233
+ )
234
+ ctx.effect(
235
+ () =>
236
+ ctx.slots.inject('sidebar.panellist', () =>
237
+ ctx.slots.register({ name: 'sidebar.panellist', id: PANEL_ID, order: 46, label: '临时目录' }, TempDirIcon),
238
+ ),
239
+ 'session-task-tmpdir: sidebar entry',
240
+ )
241
+ },
242
+ }
243
+ },
244
+ })
package/cordis.patch.yml CHANGED
@@ -12,6 +12,8 @@
12
12
  cleanupDryRun: false
13
13
  # v0.5:除 _tmp 外的长期落点必须经用户同意(longterm_approve)才能写
14
14
  requireApprovalOutsideTmp: true
15
+ # v0.9(方案3):已存在的文件视为"改写",直接放行、不弹窗;false = 改写也要求审批
16
+ allowOverwrite: true
15
17
  # 无需审批即可写的根目录名(支持 * ? 通配):插件源码目录
16
18
  allowRootPatterns:
17
19
  - dsh-*
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, statSync, writeFileSync } from 'node:fs'
1
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
2
2
  import { appendFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
3
3
  import { homedir, tmpdir } from 'node:os'
4
4
  import { basename, dirname, isAbsolute, join, parse, resolve } from 'node:path'
@@ -130,6 +130,13 @@ 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
132
  /\b(?:New-Item|mkdir|md(?=\s)|Copy-Item|Move-Item|Set-Content|Add-Content|Out-File|Expand-Archive|Invoke-WebRequest|Invoke-RestMethod|curl|wget|robocopy|git\s+clone|tar|unzip|7z|touch|tee|New-ItemProperty|cp|mv|ln|install|dd|rsync|scp|truncate|sed|perl|python3?|node)\b/i
133
+ /**
134
+ * v0.9: programs/APIs that write files but never match CREATE_VERB_PATTERN.
135
+ * Without this list a command like `ffmpeg … D:\out.mp4` skipped the path scan
136
+ * entirely, so a "new long-term artifact" could land without asking.
137
+ */
138
+ const WRITE_PROGRAM_PATTERN =
139
+ /\b(?:ffmpeg|ffmpeg\.exe|pandoc|soffice|libreoffice|wkhtmltopdf|magick|convert|gs|zip|rar|Export-Csv|Export-Clixml|Export-Pdf|WriteAllText|WriteAllBytes|WriteAllLines|AppendAllText|AppendAllBytes|CreateText|OpenWrite|Start-Process)\b/i
133
140
  /** Redirection source shared by the global form. */
134
141
  const REDIRECT_SOURCE =
135
142
  '(?:^|[\\s;&|])(?:>>|\\d?>>?)\\s*(?:"([^"]+)"|\'([^\']+)\'|([^\\s;&|]+))'
@@ -209,6 +216,8 @@ function readConfig(config) {
209
216
  const guardCodeTools = c.guardCodeTools !== false
210
217
  /** Also inspect tools the plugin does not know by name, using their schema/description. */
211
218
  const guardUnknownTools = c.guardUnknownTools !== false
219
+ /** v0.9(方案3):已存在的文件视为"改写",不弹窗;false = 改写也要审批。 */
220
+ const allowOverwrite = c.allowOverwrite !== false
212
221
  /** Extra tool names per channel, appended to the built-in sets. */
213
222
  const extraWriteTools = toStringList(c.writeToolNames, [])
214
223
  const extraPublishTools = toStringList(c.publishToolNames, [])
@@ -233,6 +242,7 @@ function readConfig(config) {
233
242
  publishGuard,
234
243
  guardCodeTools,
235
244
  guardUnknownTools,
245
+ allowOverwrite,
236
246
  writeToolNames: [...new Set([...WRITE_TOOL_NAMES, ...extraWriteTools])],
237
247
  publishToolNames: [...new Set([...PUBLISH_TOOL_NAMES, ...extraPublishTools])],
238
248
  codeToolNames: [...new Set([...CODE_TOOL_NAMES, ...extraCodeTools])],
@@ -326,9 +336,40 @@ export function pathInside(parent, child) {
326
336
  return c === p || c.startsWith(`${p}/`)
327
337
  }
328
338
 
339
+ /**
340
+ * v0.9: an approved target is either one exact file (`kind:'file'`) or a directory
341
+ * prefix (`kind:'dir'`, backwards compatible with the old string entries).
342
+ */
343
+ export function matchesApprovedTarget(abs, targets) {
344
+ if (typeof abs !== 'string' || !abs.trim()) return false
345
+ for (const entry of targets ?? []) {
346
+ if (entry === null || entry === undefined) continue
347
+ const path = typeof entry === 'string' ? entry : entry.path
348
+ if (typeof path !== 'string' || !path.trim()) continue
349
+ const kind = typeof entry === 'string' ? 'dir' : entry.kind === 'file' ? 'file' : 'dir'
350
+ if (kind === 'file' ? samePath(path, abs) : pathInside(path, abs)) return true
351
+ }
352
+ return false
353
+ }
354
+
355
+ /**
356
+ * v0.9(方案3):是否已存在的普通文件。改写已有文件不弹窗,只有"新建产物"才问用户。
357
+ * `pathExists` / `statPath` 可注入,便于单测。
358
+ */
359
+ export function isExistingFile(abs, options = {}) {
360
+ if (typeof abs !== 'string' || !abs.trim()) return false
361
+ const exists = typeof options.pathExists === 'function' ? options.pathExists : existsSync
362
+ const statOf = typeof options.statPath === 'function' ? options.statPath : statSync
363
+ try {
364
+ if (!exists(abs)) return false
365
+ return statOf(abs).isFile()
366
+ } catch {
367
+ return false
368
+ }
369
+ }
370
+
329
371
  /** First path segment of `abs` relative to `cwd`, or undefined when not inside `cwd`. */
330
- export function firstSegmentUnder(cwd, abs) {
331
- if (typeof cwd !== 'string' || typeof abs !== 'string') return undefined
372
+ export function firstSegmentUnder(cwd, abs) { if (typeof cwd !== 'string' || typeof abs !== 'string') return undefined
332
373
  const base = resolve(cwd)
333
374
  const target = resolve(abs)
334
375
  if (!(normalizeForCompare(base) === normalizeForCompare(target) || pathInside(base, target))) return undefined
@@ -372,7 +413,11 @@ export function longtermGuardReason(targetPath, cwd, options = {}) {
372
413
  allowRootPatterns = DEFAULT_ALLOW_ROOT_PATTERNS,
373
414
  allowRootFiles = DEFAULT_ALLOW_ROOT_FILES,
374
415
  approvedPrefixes = [],
416
+ approvedTargets = [],
417
+ allowOverwrite = true,
375
418
  requireApprovalOutsideTmp = true,
419
+ pathExists,
420
+ statPath,
376
421
  } = options
377
422
  if (!requireApprovalOutsideTmp) return undefined
378
423
  if (typeof targetPath !== 'string' || targetPath.trim() === '') return undefined
@@ -387,7 +432,9 @@ export function longtermGuardReason(targetPath, cwd, options = {}) {
387
432
  if (!pathInside(base, abs)) return undefined
388
433
  const tmpRoot = join(base, rootDirName)
389
434
  if (pathInside(tmpRoot, abs)) return undefined
390
- if (approvedPrefixes.some((prefix) => pathInside(prefix, abs))) return undefined
435
+ if (matchesApprovedTarget(abs, [...approvedPrefixes, ...approvedTargets])) return undefined
436
+ // v0.9(方案3):已存在的文件视为改写,直接放行,不再打断用户。
437
+ if (allowOverwrite && isExistingFile(abs, { pathExists, statPath })) return undefined
391
438
  if (samePath(dirname(abs), base)) {
392
439
  const name = basename(abs)
393
440
  if (allowRootFiles.some((entry) => entry.toLowerCase() === name.toLowerCase())) return undefined
@@ -422,6 +469,8 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
422
469
  allowRootPatterns = DEFAULT_ALLOW_ROOT_PATTERNS,
423
470
  allowRootFiles = DEFAULT_ALLOW_ROOT_FILES,
424
471
  approvedPrefixes = [],
472
+ approvedTargets = [],
473
+ allowOverwrite = true,
425
474
  outsideAllow = [],
426
475
  requireApprovalOutsideTmp = true,
427
476
  guardOutsideWorkspace = 'deny',
@@ -446,7 +495,7 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
446
495
  redirectTokens.add(token)
447
496
  }
448
497
  const hasRedirect = redirectTokens.size > 0
449
- if (!hasRedirect && !CREATE_VERB_PATTERN.test(command)) return undefined
498
+ if (!hasRedirect && !CREATE_VERB_PATTERN.test(command) && !WRITE_PROGRAM_PATTERN.test(command)) return undefined
450
499
  const base = resolve(workspaceRoot)
451
500
  const resolveBase = typeof baseDir === 'string' && baseDir.trim() ? resolve(baseDir) : base
452
501
  // v0.7 (review M3): strip `scheme://…` first — `https://` contains `s:/`, which the
@@ -460,6 +509,8 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
460
509
  allowRootPatterns,
461
510
  allowRootFiles,
462
511
  approvedPrefixes,
512
+ approvedTargets,
513
+ allowOverwrite,
463
514
  outsideAllow,
464
515
  requireApprovalOutsideTmp,
465
516
  guardOutsideWorkspace,
@@ -487,10 +538,8 @@ export function longtermCommandGuardReason(command, workspaceRoot, options = {})
487
538
  const isRedirectTarget = redirectTokens.has(raw)
488
539
  const verdict = classifyWriteTarget(abs, base, classifyOptions)
489
540
  if (verdict.kind === 'allowed' || verdict.kind === 'skip') continue
490
- // Existing targets are usually sources of a copy or files being edited; keep the
491
- // historical low-false-positive behavior — except for redirect targets, which are
492
- // always written (v0.7 review M6).
493
- if (!isRedirectTarget && pathExists(abs)) continue
541
+ // v0.9(方案3):已存在的路径 = 改写,放行(重定向目标也一样)。
542
+ if (allowOverwrite && pathExists(abs)) continue
494
543
  if (verdict.kind === 'outside') {
495
544
  if (guardOutsideWorkspace === 'warn') {
496
545
  console.info(`[session-task-tmpdir] command guard (warn): ${abs}`)
@@ -642,10 +691,14 @@ export function classifyWriteTarget(targetPath, cwd, options = {}) {
642
691
  allowRootPatterns = DEFAULT_ALLOW_ROOT_PATTERNS,
643
692
  allowRootFiles = DEFAULT_ALLOW_ROOT_FILES,
644
693
  approvedPrefixes = [],
694
+ approvedTargets = [],
695
+ allowOverwrite = true,
645
696
  outsideAllow = [],
646
697
  requireApprovalOutsideTmp = true,
647
698
  guardOutsideWorkspace = 'deny',
648
699
  baseDir: baseDirOption,
700
+ pathExists,
701
+ statPath,
649
702
  } = options
650
703
  if (!requireApprovalOutsideTmp) return { kind: 'allowed' }
651
704
  if (typeof targetPath !== 'string' || !targetPath.trim()) return { kind: 'skip' }
@@ -665,17 +718,22 @@ export function classifyWriteTarget(targetPath, cwd, options = {}) {
665
718
  if (isScratchPath(abs, rootDirName) && ((base && pathInside(base, abs)) || isSystemTempPath(abs))) {
666
719
  return { kind: 'allowed', abs, scratch: true }
667
720
  }
721
+ const approved = [...approvedPrefixes, ...approvedTargets]
722
+ if (matchesApprovedTarget(abs, approved)) return { kind: 'allowed', abs }
668
723
  if (base && pathInside(base, abs)) {
669
724
  const reason = longtermGuardReason(abs, base, {
670
725
  rootDirName,
671
726
  allowRootPatterns,
672
727
  allowRootFiles,
673
- approvedPrefixes,
674
- requireApprovalOutsideTmp,
728
+ approvedTargets: approved,
729
+ allowOverwrite,
730
+ pathExists,
731
+ statPath,
675
732
  })
676
733
  return reason ? { kind: 'inside-longterm', abs, reason } : { kind: 'allowed', abs }
677
734
  }
678
- if (approvedPrefixes.some((prefix) => pathInside(prefix, abs))) return { kind: 'allowed', abs }
735
+ // v0.9(方案3):工作区外已存在的文件 = 改写,放行。
736
+ if (allowOverwrite && isExistingFile(abs, { pathExists, statPath })) return { kind: 'allowed', abs, overwrite: true }
679
737
  if (pathGlobMatch(abs, outsideAllow)) return { kind: 'allowed', abs }
680
738
  if (guardOutsideWorkspace === 'off') return { kind: 'allowed', abs }
681
739
  return { kind: 'outside', abs }
@@ -1183,11 +1241,46 @@ export async function cleanupOrphanedTempDirs({
1183
1241
  }
1184
1242
 
1185
1243
  /** Resolve the DSH home directory (`DSH_HOME` override, else `~/.dsh`). */
1186
- export function resolveDshHome() {
1187
- const fromEnv = process.env.DSH_HOME && process.env.DSH_HOME.trim() ? process.env.DSH_HOME.trim() : ''
1244
+ export function resolveDshHome() { const fromEnv = process.env.DSH_HOME && process.env.DSH_HOME.trim() ? process.env.DSH_HOME.trim() : ''
1188
1245
  return fromEnv || join(homedir(), '.dsh')
1189
1246
  }
1190
1247
 
1248
+ /** v0.9: persisted long-term whitelist file (exact files + directory prefixes). */
1249
+ const APPROVALS_FILE = 'session-tmpdir-approvals.json'
1250
+
1251
+ /** Absolute path of the whitelist store (`<DSH_HOME>/data/session-tmpdir-approvals.json`). */
1252
+ export function approvalsFilePath() {
1253
+ return join(resolveDshHome(), 'data', APPROVALS_FILE)
1254
+ }
1255
+
1256
+ /** Load the whitelist; a missing or corrupt file means an empty whitelist. */
1257
+ export function loadApprovalsState() {
1258
+ try {
1259
+ const parsed = JSON.parse(readFileSync(approvalsFilePath(), 'utf8'))
1260
+ const entries = Array.isArray(parsed?.entries)
1261
+ ? parsed.entries.filter(
1262
+ (entry) => entry && typeof entry.path === 'string' && entry.path.trim() && typeof entry.sessionId === 'string',
1263
+ )
1264
+ : []
1265
+ return { version: 1, entries }
1266
+ } catch {
1267
+ return { version: 1, entries: [] }
1268
+ }
1269
+ }
1270
+
1271
+ /** Persist the whitelist; a failure only warns (the in-memory copy still works). */
1272
+ export function saveApprovalsState(state) {
1273
+ try {
1274
+ const file = approvalsFilePath()
1275
+ mkdirSync(dirname(file), { recursive: true })
1276
+ writeFileSync(file, `${JSON.stringify({ version: 1, entries: state.entries ?? [] }, null, 2)}\n`, 'utf8')
1277
+ return true
1278
+ } catch (error) {
1279
+ console.warn('[session-task-tmpdir] save approvals failed:', error?.message ?? error)
1280
+ return false
1281
+ }
1282
+ }
1283
+
1191
1284
  /** Best-effort fallback: collect session ids from the persisted session tree. */
1192
1285
  async function scanPersistedSessionIds() {
1193
1286
  const ids = new Set()
@@ -1338,6 +1431,7 @@ export function apply(ctx, config) {
1338
1431
  publishGuard,
1339
1432
  guardCodeTools,
1340
1433
  guardUnknownTools,
1434
+ allowOverwrite,
1341
1435
  writeToolNames,
1342
1436
  publishToolNames,
1343
1437
  codeToolNames,
@@ -1352,8 +1446,6 @@ export function apply(ctx, config) {
1352
1446
  /** Directories outside the workspace that never need approval (DSH home, caches, temp). */
1353
1447
  const outsideAllow = [...defaultOutsideAllow(resolveDshHome()), ...extraOutsideAllow]
1354
1448
  const queues = new Map()
1355
- /** sessionId → approved long-term prefixes ({ prefix, reason, basis, approvedAt }[]). */
1356
- const approvals = new Map()
1357
1449
  let sessionPersistence
1358
1450
  let workspaceRegistry
1359
1451
  try {
@@ -1419,7 +1511,7 @@ export function apply(ctx, config) {
1419
1511
 
1420
1512
  const baseDir = (cwd) => join(cwd, rootDirName)
1421
1513
 
1422
- // ── long-term approvals (per live session, in memory) ──────────────────────
1514
+ // ── long-term approvals (v0.9:持久白名单,文件级/目录级) ────────────────────
1423
1515
  const sessionKey = (session) => {
1424
1516
  try {
1425
1517
  return session?.id ? String(session.id) : ''
@@ -1428,6 +1520,71 @@ export function apply(ctx, config) {
1428
1520
  }
1429
1521
  }
1430
1522
 
1523
+ /** Persisted whitelist: `{ version, entries: [{ id, sessionId, path, kind, reason, basis, approvedAt }] }`. */
1524
+ const approvalState = loadApprovalsState()
1525
+
1526
+ function saveApprovalsNow() {
1527
+ return saveApprovalsState(approvalState)
1528
+ }
1529
+
1530
+ /** Whitelist entries that apply to this session (exact files + directory prefixes). */
1531
+ function approvedTargetsFor(session) {
1532
+ const id = sessionKey(session)
1533
+ if (!id) return []
1534
+ return approvalState.entries
1535
+ .filter((entry) => entry.sessionId === id)
1536
+ .map((entry) => ({ path: entry.path, kind: entry.kind === 'dir' ? 'dir' : 'file' }))
1537
+ }
1538
+
1539
+ /** All whitelist entries for the panel (this session and older ones). */
1540
+ function approvalEntriesForPanel() {
1541
+ return approvalState.entries.map((entry) => ({
1542
+ id: entry.id,
1543
+ sessionId: entry.sessionId,
1544
+ path: entry.path,
1545
+ kind: entry.kind === 'dir' ? 'dir' : 'file',
1546
+ reason: entry.reason ?? '',
1547
+ basis: entry.basis ?? '',
1548
+ approvedAt: entry.approvedAt ?? 0,
1549
+ }))
1550
+ }
1551
+
1552
+ function registerApproval(session, targetPath, { reason, basis, kind = 'file' } = {}) {
1553
+ const id = sessionKey(session)
1554
+ if (!id) throw new Error('longterm_approve: session is unavailable')
1555
+ const normalized = resolve(targetPath)
1556
+ const entryKind = kind === 'dir' ? 'dir' : 'file'
1557
+ const known = approvalState.entries.some(
1558
+ (entry) =>
1559
+ entry.sessionId === id &&
1560
+ (entry.kind === 'dir' ? 'dir' : 'file') === entryKind &&
1561
+ normalizeForCompare(entry.path) === normalizeForCompare(normalized),
1562
+ )
1563
+ if (!known) {
1564
+ approvalState.entries.push({
1565
+ id: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
1566
+ sessionId: id,
1567
+ path: normalized,
1568
+ kind: entryKind,
1569
+ reason: reason ?? '',
1570
+ basis: basis ?? 'user_confirmed',
1571
+ approvedAt: Date.now(),
1572
+ })
1573
+ saveApprovalsNow()
1574
+ console.info(`[session-task-tmpdir] longterm approved (${entryKind}) ${normalized} (session ${id})`)
1575
+ }
1576
+ return approvalState.entries.filter((entry) => entry.sessionId === id)
1577
+ }
1578
+
1579
+ /** Remove one whitelist entry (the panel's only mutation). */
1580
+ function revokeApproval(entryId) {
1581
+ const before = approvalState.entries.length
1582
+ approvalState.entries = approvalState.entries.filter((entry) => entry.id !== entryId)
1583
+ if (approvalState.entries.length === before) return false
1584
+ saveApprovalsNow()
1585
+ return true
1586
+ }
1587
+
1431
1588
  /**
1432
1589
  * v0.8 claim-on-write: attribute unmarked `<rootDirName>/<dir>/` folders touched by
1433
1590
  * this session's writes to the session, so every folder the model creates joins the
@@ -1445,23 +1602,8 @@ export function apply(ctx, config) {
1445
1602
  }
1446
1603
  }
1447
1604
 
1448
- function approvedPrefixesFor(session) {
1449
- const id = sessionKey(session)
1450
- const list = id ? approvals.get(id) : undefined
1451
- return list ? list.map((entry) => entry.prefix) : []
1452
- }
1453
-
1454
- function registerApproval(session, prefix, { reason, basis }) {
1455
- const id = sessionKey(session)
1456
- if (!id) throw new Error('longterm_approve: session is unavailable')
1457
- const list = approvals.get(id) ?? []
1458
- const normalized = resolve(prefix)
1459
- if (!list.some((entry) => normalizeForCompare(entry.prefix) === normalizeForCompare(normalized))) {
1460
- list.push({ prefix: normalized, reason: reason ?? '', basis: basis ?? 'user_confirmed', approvedAt: Date.now() })
1461
- approvals.set(id, list)
1462
- console.info(`[session-task-tmpdir] longterm approved ${normalized} (session ${id})`)
1463
- }
1464
- return list
1605
+ function approvedPrefixesFor() {
1606
+ return []
1465
1607
  }
1466
1608
 
1467
1609
  async function isDir(path) {
@@ -1586,13 +1728,7 @@ export function apply(ctx, config) {
1586
1728
  }),
1587
1729
  )
1588
1730
 
1589
- // Drop per-session long-term approvals once the session is gone.
1590
- ctx.effect(() =>
1591
- ctx.on('session/disposed', (session) => {
1592
- const id = sessionKey(session)
1593
- if (id) approvals.delete(id)
1594
- }),
1595
- )
1731
+ // 白名单是持久存储(v0.9):会话 disposed(含重启)时不再清理;删除会话的条目由清理任务回收。
1596
1732
 
1597
1733
  // ── orphan cleanup ─────────────────────────────────────────────────────────
1598
1734
  let cleaning = false
@@ -1865,6 +2001,15 @@ export function apply(ctx, config) {
1865
2001
  /* registry unavailable this tick */
1866
2002
  }
1867
2003
  const existingSessionIds = await collectPersistedSessionIds()
2004
+ // v0.9:回收"会话已被删除"的白名单条目(live 与 persisted 会话都保留)。
2005
+ try {
2006
+ const aliveIds = new Set([...liveSessionIds, ...existingSessionIds].map((id) => String(id)))
2007
+ const before = approvalState.entries.length
2008
+ approvalState.entries = approvalState.entries.filter((entry) => aliveIds.has(entry.sessionId))
2009
+ if (approvalState.entries.length !== before) saveApprovalsNow()
2010
+ } catch {
2011
+ // pruning the whitelist is best-effort
2012
+ }
1868
2013
  const report = await cleanupOrphanedTempDirs({
1869
2014
  roots,
1870
2015
  rootDirName,
@@ -1930,37 +2075,115 @@ export function apply(ctx, config) {
1930
2075
  `This session's task name is its session title. Put every scratch artifact (downloaded files, generated HTML/JSON/CSV, screenshots, debug logs, intermediate data) in \`${rootDirName}/<session title>/\` under the session working directory — never in the working-directory root.`,
1931
2076
  'Call the `task_tmpdir` tool to obtain the exact current absolute path: it creates the folder and renames it automatically when the session title changes, so always fetch the path again instead of hardcoding it.',
1932
2077
  '',
1933
- '### Long-term files need the user’s approval first',
2078
+ '### Long-term files: new artifacts need approval, overwriting an existing file does not',
1934
2079
  '',
1935
2080
  'A file is "long-term" only when it must survive this session: reusable scripts/configs, cross-session records or backups, finished documents/reports the user will keep, or anything the user asks to keep. Everything else is scratch → `' +
1936
2081
  rootDirName +
1937
2082
  '/` and must NOT trigger a question.',
1938
- `Before writing a long-term file **outside** \`${rootDirName}/\`, you MUST ask the user with \`ask_user_question\` (multiple choice; the free-text answer box lets the user type any other location), for example:`,
2083
+ `v0.9 rule (方案3): **creating a new file outside \`${rootDirName}/\` requires the user's approval**; **overwriting an existing file is allowed without asking**. Approval is per file by default (\`longterm_approve\` mode=file); mode=dir approves the whole directory.`,
2084
+ `Before creating a new long-term file outside \`${rootDirName}/\`, you MUST ask the user with \`ask_user_question\` (multiple choice; the free-text answer box lets the user type any other location), for example:`,
1939
2085
  '- A. 不长期保存',
1940
2086
  '- B. 工作区根目录保存',
1941
2087
  `Keep the option labels short exactly like the two above; put the explanation in each option's \`description\` instead (A: 放 ${rootDirName}/<会话标题>/,临时目录,随会话删除后 ${orphanCleanupDays} 天清理;B: 长期保存到会话工作区根目录下). Never stuff the path details into the label.`,
1942
- 'Do not write anything until the user answers.',
1943
- 'Picking B: keep it under the workspace root; pick a clear folder name yourself, call `longterm_approve` on it, then write — no need to ask the user to confirm the folder name (same as how DSH normally names things).',
2088
+ 'Do not create anything until the user answers.',
2089
+ 'Picking B: pick a clear file path under the workspace root, call `longterm_approve` with it (mode=file by default), then write it.',
1944
2090
  'Any answer other than A/B (e.g. a path the user typed in the free-text box) is a designated location: if it is missing or ambiguous, ask the user to confirm it before calling `longterm_approve` — never guess.',
1945
- 'After the user picks a long-term location (or when the task itself already named that location), call `longterm_approve` with that directory, then write there.',
1946
- `If the user declines, says temporary, or the content is scratch: call \`task_tmpdir\` and write under \`${rootDirName}/<会话标题>/\`. Never invent a workspace-root folder instead.`,
1947
- '',
1948
- `The workspace root is guarded for both tool families: \`write\`/\`edit\` and shell tools (\`pwsh\`/\`bash\`) are denied when they would create something outside \`${rootDirName}/\` that the session has not approved. Allowed without approval: \`${rootDirName}/\`, approved long-term directories, existing plugin-source trees (${allowRootPatterns.join(', ')}), and root files ${allowRootFiles.join(', ') || '(none)'}.`,
2091
+ '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.',
2092
+ `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.`,
1949
2093
  '',
1950
- '### What the write guard covers (v0.7)',
2094
+ `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.`,
1951
2095
  '',
1952
- 'The rule is enforced at the tool layer, not only in this text. Checked channels:',
1953
- '- `write` / `edit` path arguments;',
1954
- '- `publish` delivery copies (`source` → `target`, e.g. HarmonyOS `Download/<package>/`); `present` only displays an existing file and is not a write;',
1955
- '- shell tools (`pwsh` / `bash`): literal absolute paths in commands that create something;',
1956
- '- code-execution tools (`python` / `node` / …): write statements paired with path literals (static best-effort; dynamically built paths are not guaranteed);',
1957
- '- any other tool whose schema declares path arguments: a new workspace-root entry or a destination outside the workspace is denied.',
2096
+ '### Whitelist panel',
1958
2097
  '',
1959
- `Destinations outside the workspace count as long-term too. Allowed without asking: \`${rootDirName}/\`, already approved directories, DSH's own home, caches and the OS temp directory. When a write is denied, ask the user with \`ask_user_question\` and register the agreed directory with \`longterm_approve\` (it accepts directories outside the workspace as well).`,
2098
+ `Every approval is stored at \`<DSH_HOME>/data/session-tmpdir-approvals.json\` and shown in the left sidebar panel 「临时目录」 (display + remove only). Approvals survive a restart of the same session; entries whose session was deleted are pruned by the cleanup tick.`,
1960
2099
  ].join('\n'),
1961
2100
  }),
1962
2101
  )
1963
2102
 
2103
+ /** Read a small JSON body (panel POST). */
2104
+ function readRequestBody(req, limit = 32 * 1024) {
2105
+ return new Promise((resolvePromise) => {
2106
+ let data = ''
2107
+ req.on('data', (chunk) => {
2108
+ data += chunk
2109
+ if (data.length > limit) {
2110
+ data = data.slice(0, limit)
2111
+ req.destroy()
2112
+ }
2113
+ })
2114
+ req.on('end', () => {
2115
+ try {
2116
+ resolvePromise(JSON.parse(data || '{}'))
2117
+ } catch {
2118
+ resolvePromise(undefined)
2119
+ }
2120
+ })
2121
+ req.on('error', () => resolvePromise(undefined))
2122
+ })
2123
+ }
2124
+
2125
+ // 面板接口:GET /__dsh-session-tmpdir/state(白名单清单)、POST /__dsh-session-tmpdir/revoke(移除一条)。
2126
+ ctx.inject(['webServer'], (webScope) => {
2127
+ webScope.effect(
2128
+ () =>
2129
+ webScope.webServer.register({
2130
+ kind: 'prefix',
2131
+ path: '/__dsh-session-tmpdir',
2132
+ handler: async (req, res) => {
2133
+ const sendJson = (status, payload) => {
2134
+ res.statusCode = status
2135
+ res.setHeader('content-type', 'application/json; charset=utf-8')
2136
+ res.setHeader('cache-control', 'no-store')
2137
+ res.end(JSON.stringify(payload))
2138
+ }
2139
+ try {
2140
+ const rawUrl = String(req.url ?? '/')
2141
+ const queryAt = rawUrl.indexOf('?')
2142
+ const pathname = queryAt === -1 ? rawUrl : rawUrl.slice(0, queryAt)
2143
+ const sessionId = (() => {
2144
+ try {
2145
+ return new URL(rawUrl, 'http://localhost').searchParams.get('session') || ''
2146
+ } catch {
2147
+ return ''
2148
+ }
2149
+ })()
2150
+ if (pathname.endsWith('/state') && req.method === 'GET') {
2151
+ const approvals = approvalEntriesForPanel().map((entry) => ({
2152
+ ...entry,
2153
+ current: Boolean(sessionId && entry.sessionId === sessionId),
2154
+ }))
2155
+ sendJson(200, {
2156
+ ok: true,
2157
+ generatedAt: Date.now(),
2158
+ currentSessionId: sessionId,
2159
+ approvalsFile: approvalsFilePath(),
2160
+ rootDirName,
2161
+ allowOverwrite,
2162
+ approvals,
2163
+ })
2164
+ return
2165
+ }
2166
+ if (pathname.endsWith('/revoke') && req.method === 'POST') {
2167
+ const body = await readRequestBody(req)
2168
+ const id = typeof body?.id === 'string' ? body.id.trim() : ''
2169
+ if (!id) {
2170
+ sendJson(400, { ok: false, error: 'id required' })
2171
+ return
2172
+ }
2173
+ const revoked = revokeApproval(id)
2174
+ sendJson(200, { ok: true, revoked, approvals: approvalEntriesForPanel() })
2175
+ return
2176
+ }
2177
+ sendJson(404, { ok: false, error: 'not found' })
2178
+ } catch (error) {
2179
+ sendJson(500, { ok: false, error: error instanceof Error ? error.message : String(error) })
2180
+ }
2181
+ },
2182
+ }),
2183
+ 'session-task-tmpdir: panel route',
2184
+ )
2185
+ })
2186
+
1964
2187
  ctx.effect(() =>
1965
2188
  ctx.tools.register({
1966
2189
  name: 'task_tmpdir',
@@ -2000,18 +2223,24 @@ export function apply(ctx, config) {
2000
2223
  name: 'longterm_approve',
2001
2224
  description:
2002
2225
  '登记「本次会话已获用户同意的长期保存落点」。用户明确同意长期保存(或任务里已指定位置)后调用;' +
2003
- `登记后 write/edit、shell 命令、publish 交付、python 等代码工具才能写该目录(工作区内或工作区外都可以),` +
2004
- `否则会被拒绝并提示先问用户。临时产物不要用它,直接用 task_tmpdir 写 ${rootDirName}/<会话标题>/。`,
2226
+ `默认只登记这一个文件(mode=file),mode=dir 才登记整个目录。登记后 write/edit、shell 命令、publish 交付、` +
2227
+ `python 等代码工具才能新建该位置的文件;已存在的文件按"改写"直接放行,不需要登记。` +
2228
+ `临时产物不要用它,直接用 task_tmpdir 写 ${rootDirName}/<会话标题>/。`,
2005
2229
  parameters: {
2006
2230
  type: 'object',
2007
2231
  properties: {
2008
- path: { type: 'string', description: '用户指定/同意的目录绝对路径(传文件路径也行,会自动取所在目录)。' },
2232
+ path: { type: 'string', description: '用户指定/同意的绝对路径(文件或目录)。' },
2009
2233
  reason: { type: 'string', description: '为什么属于长期保存(一句话,用于日志)。' },
2010
2234
  basis: {
2011
2235
  type: 'string',
2012
2236
  enum: ['user_confirmed', 'task_designated'],
2013
2237
  description: 'user_confirmed=用户刚在选择题里同意长期保存;task_designated=用户在任务里明确指定了该位置。',
2014
2238
  },
2239
+ mode: {
2240
+ type: 'string',
2241
+ enum: ['file', 'dir'],
2242
+ description: 'file=只批准这一个文件(默认);dir=批准整个目录(该目录下新建的文件都放行)。',
2243
+ },
2015
2244
  },
2016
2245
  required: ['path'],
2017
2246
  additionalProperties: false,
@@ -2022,8 +2251,9 @@ export function apply(ctx, config) {
2022
2251
  properties: {
2023
2252
  approved: { type: 'boolean' },
2024
2253
  path: { type: 'string' },
2254
+ kind: { type: 'string' },
2025
2255
  basis: { type: 'string' },
2026
- approvedPrefixes: { type: 'array', items: { type: 'string' } },
2256
+ entries: { type: 'array', items: { type: 'object' } },
2027
2257
  },
2028
2258
  required: ['approved', 'path'],
2029
2259
  },
@@ -2070,24 +2300,27 @@ export function apply(ctx, config) {
2070
2300
  }
2071
2301
  }
2072
2302
  const basis = args?.basis === 'task_designated' ? 'task_designated' : 'user_confirmed'
2073
- let directory = abs
2074
- try {
2075
- if (existsSync(abs)) {
2076
- if (!statSync(abs).isDirectory()) directory = dirname(abs)
2077
- } else if (FILE_EXTENSION_PATTERN.test(basename(abs))) {
2078
- // v0.7 (review A9): a not-yet-created file path registers its directory,
2079
- // otherwise the next file in the same folder would still be denied.
2080
- directory = dirname(abs)
2303
+ // v0.9(方案3):默认只批准"这一个文件";mode=dir 才批准整个目录。
2304
+ const requestedMode = args?.mode === 'dir' ? 'dir' : 'file'
2305
+ let kind = requestedMode
2306
+ if (requestedMode === 'file') {
2307
+ try {
2308
+ if (existsSync(abs)) {
2309
+ if (statSync(abs).isDirectory()) kind = 'dir'
2310
+ } else {
2311
+ kind = FILE_EXTENSION_PATTERN.test(basename(abs)) ? 'file' : 'dir'
2312
+ }
2313
+ } catch {
2314
+ // 保留默认 kind
2081
2315
  }
2082
- } catch {
2083
- // keep the passed path
2084
2316
  }
2085
- const list = registerApproval(session, directory, { reason: args?.reason, basis })
2317
+ const list = registerApproval(session, abs, { reason: args?.reason, basis, kind })
2086
2318
  return {
2087
2319
  approved: true,
2088
- path: directory,
2320
+ path: abs,
2321
+ kind,
2089
2322
  basis,
2090
- approvedPrefixes: list.map((entry) => entry.prefix),
2323
+ entries: list.map((entry) => ({ path: entry.path, kind: entry.kind })),
2091
2324
  }
2092
2325
  },
2093
2326
  }),
@@ -2201,12 +2434,13 @@ export function apply(ctx, config) {
2201
2434
  // working directory being a registered workspace root. Destinations outside
2202
2435
  // the workspace are checked even when the session `cd`-ed into a subfolder.
2203
2436
  const protectedRoot = isProtectedRoot(cwd)
2204
- const approvedPrefixes = approvedPrefixesFor(session)
2437
+ const approvedTargets = approvedTargetsFor(session)
2205
2438
  const classifyOptions = {
2206
2439
  rootDirName,
2207
2440
  allowRootPatterns,
2208
2441
  allowRootFiles,
2209
- approvedPrefixes,
2442
+ approvedTargets,
2443
+ allowOverwrite,
2210
2444
  outsideAllow,
2211
2445
  requireApprovalOutsideTmp,
2212
2446
  guardOutsideWorkspace,
@@ -2310,10 +2544,15 @@ export function apply(ctx, config) {
2310
2544
  return undefined
2311
2545
  }
2312
2546
 
2313
- // unknown but write-capable tools: only the two high-risk destinations
2547
+ // unknown but write-capable tools: same unified rule as write/edit (v0.9).
2548
+ // 已存在的文件 = 改写,放行;未审批的新文件 → 拒绝并提示先问用户。
2314
2549
  if (plan.channel === 'unknown') {
2315
2550
  for (const target of collectPathTargets(args, { schema })) {
2316
2551
  const verdict = classifyWriteTarget(target, cwd, classifyOptions)
2552
+ if (verdict.kind === 'inside-longterm') {
2553
+ if (!protectedRoot) continue
2554
+ return deny('longterm guard', verdict.reason)
2555
+ }
2317
2556
  if (verdict.kind === 'outside') {
2318
2557
  if (guardOutsideWorkspace === 'warn') {
2319
2558
  outsideWarn('outside guard', verdict.abs)
@@ -2322,9 +2561,6 @@ export function apply(ctx, config) {
2322
2561
  if (guardOutsideWorkspace === 'off') continue
2323
2562
  return deny('outside guard', outsideWriteDenialReason(verdict.abs, { rootDirName }))
2324
2563
  }
2325
- if (verdict.kind === 'inside-longterm' && protectedRoot && samePath(dirname(verdict.abs), resolve(cwd))) {
2326
- return deny('longterm guard', verdict.reason)
2327
- }
2328
2564
  }
2329
2565
  claimTmpTargets(collectPathTargets(args, { schema }), session)
2330
2566
  return undefined
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
- "title": "Task Temp Folder",
4
- "description": "Gives every session a task temp folder _tmp/<session title>/ in its working directory, renames it whenever the session title changes, and deletes it 7 days after the session is deleted; the same pass also reclaims that session's attachments. v0.7 guards every write channel (write/edit, shell, publish delivery copies, embedded code runtimes, unknown write-capable tools) and treats destinations outside the workspace as long-term too."
3
+ "title": "Temp Folder",
4
+ "description": "Gives every session a task temp folder _tmp/<session title>/ in its working directory, renames it whenever the session title changes, and deletes it 7 days after the session is deleted; the same pass also reclaims that session's attachments. v0.9 splits scratch vs long-term artifacts: creating a new file outside _tmp asks the user first (per-file approval by default), overwriting an existing file is allowed; write/edit, shell (including ffmpeg-like programs), publish copies, code runtimes and unknown write-capable tools share the same guard, and the persisted whitelist is shown (and removable) in the left-sidebar 「临时目录」 panel."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
- "title": "任务临时目录",
4
- "description": "给每个会话一个任务临时目录 _tmp/<会话标题>/,会话改名时自动同步重命名;会话删除 7 天后自动清理对应目录,并回收该会话独占的附件。v0.7 起守住所有写入通道(write/edit、shell、publish 交付、python 等代码工具、未知写类工具),工作区外的落点也算长期保存,未经用户同意一律拒绝。"
3
+ "title": "临时目录",
4
+ "description": "给每个会话一个任务临时目录 _tmp/<会话标题>/,会话改名时自动同步重命名;会话删除 7 天后自动清理对应目录,并回收该会话独占的附件。v0.9 按中间产物/长期产物划分:_tmp 外新建文件先问用户(默认文件级审批),改写已存在文件直接放行;write/edit、shell(含 ffmpeg 等程序)、publish 交付、代码工具、未知写类工具受同一个 guard 约束,白名单在左侧「临时目录」面板展示并可移除。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,15 +1,17 @@
1
1
  {
2
2
  "name": "@leiyi-works/dsh-session-tmpdir",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "type": "module",
5
- "description": "Per-session task temp folder: every session gets _tmp/<session title>/ in its working directory, auto-created and auto-renamed with the session title; folders are deleted 7 days after the session is deleted, and the same tick reclaims the attachment store. v0.7 also guards every write channel: write/edit, shell commands (Windows drive paths and HarmonyOS/POSIX paths), publish delivery copies, embedded code runtimes (python/node, static scan) and unknown tools that declare path arguments. Destinations outside the workspace are long-term too — without the user's approval (longterm_approve) the call is denied and the model is told to ask first, then fall back to _tmp.",
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": {
7
7
  ".": "./index.js",
8
+ "./client": "./client.js",
8
9
  "./locale/*.json": "./locale/*.json",
9
10
  "./icon": "./icon.svg"
10
11
  },
11
12
  "files": [
12
13
  "index.js",
14
+ "client.js",
13
15
  "cordis.patch.yml",
14
16
  "README.md",
15
17
  "locale/*.json",
@@ -18,6 +20,20 @@
18
20
  "dsh": {
19
21
  "bundle": {
20
22
  "patch": "./cordis.patch.yml"
23
+ },
24
+ "client": {
25
+ "platform": "web",
26
+ "immediately": true,
27
+ "inject": [
28
+ "@deepseek-ai/dsh-client-modules",
29
+ "@deepseek-ai/dsh-client-locale",
30
+ "@deepseek-ai/dsh-client-ui-slots",
31
+ "@deepseek-ai/dsh-client-ui-conversation",
32
+ "@deepseek-ai/dsh-client-ui-layout",
33
+ "@deepseek-ai/dsh-client-ui-sidebar",
34
+ "@deepseek-ai/dsh-client-ui-sidebar-right",
35
+ "@deepseek-ai/dsh-client-ui-settings"
36
+ ]
21
37
  }
22
38
  },
23
39
  "license": "MIT",