@leiyi-works/dsh-session-tmpdir 0.11.1 → 0.12.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 (4) hide show
  1. package/README.md +12 -2
  2. package/client.js +130 -16
  3. package/index.js +94 -3
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -73,7 +73,7 @@ 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/tmpdir-guard/approvals.json`:**按会话生效**——同一会话重启、同一会话换机续用都继续有效;其他会话即使路径相同也不会自动放行;会话被删除的条目由清理任务回收。左侧菜单「临时目录」面板只做展示与「移除」(移除后该文件下次新建会重新走审批),不提供手动添加(添加只能来自对话里的用户同意)。
76
+ 白名单**持久保存**在 `<DSH_HOME>/data/tmpdir-guard/approvals.json`:**按会话生效**——同一会话重启、同一会话换机续用都继续有效;其他会话即使路径相同也不会自动放行;会话被删除的条目由清理任务回收。左侧菜单「临时目录」面板只做展示与「移除」(移除后该文件下次新建会重新走审批),不提供手动添加(添加只能来自对话里的用户同意)。面板还会列出**最近被 guard 拦下的写操作**(v0.12.0),侧栏图标上的红点表示有新的拦截未看过;记录同时追加到 `<DSH_HOME>/data/tmpdir-guard/denials.jsonl`。
77
77
 
78
78
  ## guard 行为边界(v0.11)
79
79
 
@@ -354,4 +354,14 @@ v0.10.3 变更(2026-11-16):
354
354
  1. **恢复 0.10.16 的分段语义**(`;` / `&&` / `||` / `|` / 换行切分);引号内文本只通过**整条命令的引号区间**参与“动态写目标屏蔽”,不改变字面量通道与代码静态扫描的旧判定。
355
355
  2. **保留 0.11.0 的全部收益**:变量/环境变量/`~` 写目标解析、注释剥离、here-string/heredoc 内容屏蔽、`> $null` 处理、`ni`/`md` 修正等都不变。
356
356
  3. **回放结果**:2798 条历史命令里新旧判定只有 **16 条不同**——13 条是“变量指向工作区根新文件/新建工作区子目录”(这些写法换成字面量在 0.10.16 本来就会被拒,属规则内),另 3 条是本次测试探针;`_tmp`/审批目录/DSH home 没有新增拒绝。另有 **13 条旧版误报被修好**(`> $null` 被当成 `D:\dev\null`、`> $dir\…` 被当工作区相对路径等)。
357
- 4. **回归测试**:`test/guard.test.mjs` **115 条**;`test/diff.test.mjs` **79 条**(含历史回放的代表性写法)。
357
+ 4. **回归测试**:`test/guard.test.mjs` **115 条**;`test/diff.test.mjs` **79 条**(含历史回放的代表性写法)。
358
+
359
+ ## v0.12.0 变更(2026-11-20):被 guard 拦下的写操作在面板里可见
360
+
361
+ 背景:用户不读工具调用细节,无法判断 guard 是否误拦了正常任务。现在每次拦截都会留下用户可见的记录。
362
+
363
+ 1. 侧栏「临时目录」图标右上角显示红点数字 = **未看过的新拦截数**(最多显示 99+),每 8 秒刷新;打开面板即视为看过并清除红点。
364
+ 2. 面板新增「最近被拦下的写操作」:时间、目标路径、拦截类别(工作区外/工作区根/工作区目录/长期位置)、工具名、会话标题、命令片段(最长 200 字符);内存里保留最近 100 条。
365
+ 3. 同时 best-effort 追加审计文件 `<DSH_HOME>/data/tmpdir-guard/denials.jsonl`(每行一条 JSON;文件写不进去不影响判定)。
366
+ 4. `GET /__dsh-session-tmpdir/state` 返回 `denials` 字段;`POST /__dsh-session-tmpdir/ack-denials` 标记已看过。**guard 判定逻辑本身未改**。
367
+ 5. 提醒:拦截 ≠ 任务失败——模型收到拒绝提示后会改用 `_tmp` 或先征求同意再继续;面板里的记录用于让你判断"这次是不是误拦"。
package/client.js CHANGED
@@ -91,6 +91,30 @@ window.__ModuleLoader__.load({
91
91
  },
92
92
  empty: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)', margin: '8px 0 0' },
93
93
  err: { fontSize: 12, color: 'var(--dsw-alias-state-error-primary, #d14a4a)', margin: 0 },
94
+ subTitle: { margin: '10px 0 0', fontSize: 13, fontWeight: 600 },
95
+ badge: {
96
+ position: 'absolute',
97
+ top: -3,
98
+ right: -4,
99
+ minWidth: 14,
100
+ height: 14,
101
+ padding: '0 3px',
102
+ boxSizing: 'border-box',
103
+ borderRadius: 999,
104
+ background: 'var(--dsw-alias-state-error-primary, #d14a4a)',
105
+ color: '#fff',
106
+ fontSize: 9,
107
+ lineHeight: '14px',
108
+ textAlign: 'center',
109
+ fontWeight: 600,
110
+ },
111
+ }
112
+
113
+ function denialKindLabel(kind) {
114
+ if (kind === 'outside') return '工作区外'
115
+ if (kind === 'workspace-root') return '工作区根'
116
+ if (kind === 'workspace-dir') return '工作区目录'
117
+ return '长期位置'
94
118
  }
95
119
 
96
120
  function fmtTime(ms) {
@@ -167,6 +191,63 @@ window.__ModuleLoader__.load({
167
191
 
168
192
  const data = state.data
169
193
  const rows = data && Array.isArray(data.approvals) ? data.approvals : []
194
+ const denials = data && data.denials && typeof data.denials === 'object' ? data.denials : null
195
+ const denialItems = denials && Array.isArray(denials.items) ? denials.items : []
196
+ const unseenDenials = denials ? Math.max(0, Number(denials.unseen) || 0) : 0
197
+
198
+ // v0.12.0:打开面板即视为“看过”拦截记录 —— 清掉侧栏红点,但列表保留本次显示。
199
+ React.useEffect(() => {
200
+ if (!denials || unseenDenials <= 0) return undefined
201
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return undefined
202
+ const timer = setTimeout(() => {
203
+ void fetch(`${API}/ack-denials`, { method: 'POST' })
204
+ .then(() => load(true))
205
+ .catch(() => {})
206
+ }, 1200)
207
+ return () => clearTimeout(timer)
208
+ }, [denials, unseenDenials, load])
209
+
210
+ const denialNodes = denialItems.map((item) =>
211
+ h(
212
+ 'div',
213
+ { key: item.id, style: styles.row },
214
+ h(
215
+ 'div',
216
+ { style: styles.rowMain },
217
+ h('div', { style: styles.path }, item.path || '(未解析出路径)'),
218
+ h(
219
+ 'div',
220
+ { style: styles.rowMeta },
221
+ h('span', { style: styles.tagWarn }, denialKindLabel(item.kind)),
222
+ h(
223
+ 'span',
224
+ { style: styles.meta },
225
+ `${item.tool || '工具'}${item.sessionTitle ? ` · 会话「${item.sessionTitle}」` : ''}`,
226
+ ),
227
+ h('span', { style: styles.meta }, fmtTime(item.at)),
228
+ ),
229
+ item.command ? h('div', { style: styles.meta }, item.command) : null,
230
+ ),
231
+ ),
232
+ )
233
+
234
+ const denialsSection = h(
235
+ 'div',
236
+ null,
237
+ h(
238
+ 'h2',
239
+ { style: styles.subTitle },
240
+ `最近被拦下的写操作${denials && denials.total > 0 ? `(共 ${denials.total} 次,未看 ${unseenDenials})` : ''}`,
241
+ ),
242
+ denialItems.length === 0
243
+ ? h('p', { style: styles.empty }, '没有拦截记录 —— 插件没有打断任何写入。')
244
+ : h('div', { style: styles.table }, ...denialNodes),
245
+ h(
246
+ 'p',
247
+ { style: styles.meta },
248
+ '这些是 guard 为“新建文件先问 / 改用 _tmp”而拒绝的操作,模型会自动换正确路径继续。侧栏图标上的红点 = 有新的拦截未看过;打开本面板即清除。',
249
+ ),
250
+ )
170
251
 
171
252
  const metaLine = data
172
253
  ? h(
@@ -233,6 +314,8 @@ window.__ModuleLoader__.load({
233
314
  ),
234
315
  ),
235
316
  state.error ? h('p', { style: styles.err }, state.error) : null,
317
+ denialsSection,
318
+ h('h2', { style: styles.subTitle }, '长期落点白名单'),
236
319
  rows.length === 0
237
320
  ? h('p', { style: styles.empty }, state.loading ? '' : '白名单为空。')
238
321
  : h('div', { style: styles.table }, ...rowNodes),
@@ -242,23 +325,54 @@ window.__ModuleLoader__.load({
242
325
 
243
326
  function TempDirIcon(props) {
244
327
  const size = typeof props?.size === 'number' && props.size > 0 ? props.size : 18
328
+ // v0.12.0:未看过的 guard 拦截数 → 图标红点(用户不必读工具调用细节也能看到)。
329
+ const [unseen, setUnseen] = React.useState(0)
330
+ React.useEffect(() => {
331
+ let alive = true
332
+ const tick = async () => {
333
+ try {
334
+ const res = await fetch(`${API}/state`, { cache: 'no-store' })
335
+ const data = await res.json()
336
+ if (alive && data && data.ok === true) {
337
+ setUnseen(Math.max(0, Number(data?.denials?.unseen) || 0))
338
+ }
339
+ } catch {
340
+ // 面板接口不可用时保持原状
341
+ }
342
+ }
343
+ void tick()
344
+ const timer = setInterval(tick, 8000)
345
+ return () => {
346
+ alive = false
347
+ clearInterval(timer)
348
+ }
349
+ }, [])
350
+ const badge =
351
+ unseen > 0
352
+ ? h('span', { style: styles.badge, title: `${unseen} 条新的拦截记录` }, unseen > 99 ? '99+' : String(unseen))
353
+ : null
245
354
  return h(
246
- 'svg',
247
- {
248
- width: size,
249
- height: size,
250
- viewBox: '0 0 24 24',
251
- fill: 'none',
252
- 'aria-hidden': true,
253
- style: { display: 'block' },
254
- },
255
- h('path', {
256
- d: 'M6.5 4.5h11M6.5 19.5h11M8.3 4.5v3.4c0 1.9 1.7 3.4 3.7 5 2-1.6 3.7-3.1 3.7-5V4.5M8.3 19.5v-3.4c0-1.9 1.7-3.4 3.7-5 2 1.6 3.7 3.1 3.7 5v3.4',
257
- stroke: 'currentColor',
258
- strokeWidth: 1.6,
259
- strokeLinecap: 'round',
260
- strokeLinejoin: 'round',
261
- }),
355
+ 'span',
356
+ { style: { position: 'relative', display: 'inline-flex' } },
357
+ h(
358
+ 'svg',
359
+ {
360
+ width: size,
361
+ height: size,
362
+ viewBox: '0 0 24 24',
363
+ fill: 'none',
364
+ 'aria-hidden': true,
365
+ style: { display: 'block' },
366
+ },
367
+ h('path', {
368
+ d: 'M6.5 4.5h11M6.5 19.5h11M8.3 4.5v3.4c0 1.9 1.7 3.4 3.7 5 2-1.6 3.7-3.1 3.7-5V4.5M8.3 19.5v-3.4c0-1.9 1.7-3.4 3.7-5 2 1.6 3.7 3.1 3.7 5v3.4',
369
+ stroke: 'currentColor',
370
+ strokeWidth: 1.6,
371
+ strokeLinecap: 'round',
372
+ strokeLinejoin: 'round',
373
+ }),
374
+ ),
375
+ badge,
262
376
  )
263
377
  }
264
378
 
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
1
+ import { appendFileSync, 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, hostname, tmpdir } from 'node:os'
4
4
  import { basename, dirname, isAbsolute, join, parse, resolve } from 'node:path'
@@ -1419,9 +1419,27 @@ export function outsideWriteDenialReason(abs, options = {}) {
1419
1419
  )
1420
1420
  }
1421
1421
 
1422
+ /**
1423
+ * v0.12.0: extract the denied target path from a guard denial message, so the panel can
1424
+ * show "what was blocked" without parsing log lines by hand.
1425
+ */
1426
+ export function denialTargetPath(reason) {
1427
+ const text = String(reason ?? '')
1428
+ const match = /(((?:[A-Za-z]:[\\/]|\/|\\\\)[^)]{1,500}))/.exec(text)
1429
+ return match ? match[1].trim() : ''
1430
+ }
1431
+
1432
+ /** v0.12.0: classify a denial message (used by the panel's denial list). */
1433
+ export function denialKind(reason) {
1434
+ const text = String(reason ?? '')
1435
+ if (text.includes('工作区之外')) return 'outside'
1436
+ if (text.includes('工作区根目录')) return 'workspace-root'
1437
+ if (text.includes('工作区里的')) return 'workspace-dir'
1438
+ return 'long-term'
1439
+ }
1440
+
1422
1441
  /** Argument names that name a write destination strongly (bare file names are allowed). */
1423
- const STRONG_TARGET_KEYS = new Set([
1424
- 'target',
1442
+ const STRONG_TARGET_KEYS = new Set([ 'target',
1425
1443
  'targets',
1426
1444
  'target_path',
1427
1445
  'destination',
@@ -3039,6 +3057,72 @@ export function apply(ctx, config) {
3039
3057
  })
3040
3058
  }
3041
3059
 
3060
+ // ── v0.12.0: guard denial audit(面板可见 + 侧栏红点)────────────────────
3061
+ // 用户不读工具调用细节,所以被 guard 拦下的写操作要有一个用户能一眼看到的出口:
3062
+ // 左侧「临时目录」图标上的红点(未看过的新拦截数)+ 面板里的「最近拦截」列表。
3063
+ // 内存里保留最近 100 条;同时 best-effort 追加到 data/tmpdir-guard/denials.jsonl。
3064
+ const DENIAL_LOG_LIMIT = 100
3065
+ const denialLog = []
3066
+ const denialLogFile = join(resolveDshHome(), 'data', 'tmpdir-guard', 'denials.jsonl')
3067
+ let denialSeenAt = 0
3068
+ let denialTotal = 0
3069
+ let denialSeq = 0
3070
+
3071
+ function recordGuardDenial({ toolName, label, reason, session, execution }) {
3072
+ try {
3073
+ denialSeq += 1
3074
+ denialTotal += 1
3075
+ const args = execution && typeof execution.arguments === 'object' ? execution.arguments : undefined
3076
+ const command = (() => {
3077
+ if (!args || typeof args !== 'object') return ''
3078
+ const value =
3079
+ typeof args.command === 'string'
3080
+ ? args.command
3081
+ : typeof args.file_path === 'string'
3082
+ ? args.file_path
3083
+ : typeof args.path === 'string'
3084
+ ? args.path
3085
+ : typeof args.code === 'string'
3086
+ ? args.code
3087
+ : ''
3088
+ return String(value).replace(/\s+/g, ' ').trim().slice(0, 200)
3089
+ })()
3090
+ const entry = {
3091
+ id: `deny-${Date.now().toString(36)}-${denialSeq.toString(36)}`,
3092
+ at: Date.now(),
3093
+ tool: String(toolName ?? '').slice(0, 40),
3094
+ label: String(label ?? '').slice(0, 60),
3095
+ kind: denialKind(reason),
3096
+ path: denialTargetPath(reason).slice(0, 260),
3097
+ sessionId: sessionKey(session),
3098
+ sessionTitle: titleOf(session) ?? '',
3099
+ command,
3100
+ }
3101
+ denialLog.push(entry)
3102
+ if (denialLog.length > DENIAL_LOG_LIMIT) denialLog.splice(0, denialLog.length - DENIAL_LOG_LIMIT)
3103
+ try {
3104
+ mkdirSync(dirname(denialLogFile), { recursive: true })
3105
+ appendFileSync(denialLogFile, `${JSON.stringify(entry)}\n`)
3106
+ } catch {
3107
+ // the audit file is best-effort
3108
+ }
3109
+ } catch {
3110
+ // recording must never change a guard verdict
3111
+ }
3112
+ }
3113
+
3114
+ function denialSnapshot() {
3115
+ const lastAt = denialLog.length > 0 ? denialLog[denialLog.length - 1].at : 0
3116
+ return {
3117
+ seenAt: denialSeenAt,
3118
+ total: denialTotal,
3119
+ unseen: denialLog.filter((entry) => entry.at > denialSeenAt).length,
3120
+ lastAt,
3121
+ file: denialLogFile,
3122
+ items: denialLog.slice(-50).reverse(),
3123
+ }
3124
+ }
3125
+
3042
3126
  // 面板接口:GET /__dsh-session-tmpdir/state(白名单清单)、POST /__dsh-session-tmpdir/revoke(移除一条)。
3043
3127
  ctx.inject(['webServer'], (webScope) => {
3044
3128
  webScope.effect(
@@ -3079,9 +3163,15 @@ export function apply(ctx, config) {
3079
3163
  rootDirName,
3080
3164
  allowOverwrite,
3081
3165
  approvals,
3166
+ denials: denialSnapshot(),
3082
3167
  })
3083
3168
  return
3084
3169
  }
3170
+ if (pathname.endsWith('/ack-denials') && req.method === 'POST') {
3171
+ denialSeenAt = Date.now()
3172
+ sendJson(200, { ok: true, denials: denialSnapshot() })
3173
+ return
3174
+ }
3085
3175
  if (pathname.endsWith('/revoke') && req.method === 'POST') {
3086
3176
  const body = await readRequestBody(req)
3087
3177
  const id = typeof body?.id === 'string' ? body.id.trim() : ''
@@ -3366,6 +3456,7 @@ export function apply(ctx, config) {
3366
3456
  }
3367
3457
  const deny = (label, reason) => {
3368
3458
  console.info(`[session-task-tmpdir] ${label} denied: ${reason}`)
3459
+ recordGuardDenial({ toolName, label, reason, session, execution })
3369
3460
  return reason
3370
3461
  }
3371
3462
  const outsideWarn = (label, abs) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leiyi-works/dsh-session-tmpdir",
3
- "version": "0.11.1",
3
+ "version": "0.12.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": {