@leiyi-works/dsh-session-tmpdir 0.0.0-stage → 0.5.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,3 +1,79 @@
1
- # Temporary Holding Version
1
+ # Task Temp Folder(session-task-tmpdir)v0.5
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 给每个 DSH 会话一个**任务临时目录**,并在**会话被删除 7 天后**自动清掉对应目录:
4
+
5
+ ```
6
+ <会话工作目录>/_tmp/<会话标题>/
7
+ ```
8
+
9
+ 同时守住工作区根目录:**临时文件只能进 `_tmp/`;长期文件必须用户点头后才能落盘**。
10
+
11
+ ## 一句话规则(v0.5)
12
+
13
+ - 临时产物(下载文件、中间数据、截图、调试日志、一次性稿)→ `_tmp/<会话标题>/`,**不问用户**,直接写;
14
+ - 长期产物(跨会话复用/存档/交付成品)→ 先问用户(选择题);用户同意 → `longterm_approve` 登记其指定目录后写入;用户否定 → **退回 `_tmp`**;
15
+ - 未经同意的长期落点(包括在工作区根新建文件夹)→ `write`/`edit`/`pwsh`/`bash` 在**工具层直接拒绝**,并给出纠正提示。
16
+
17
+ ## 功能介绍
18
+
19
+ | 功能 | 行为 |
20
+ |---|---|
21
+ | **任务临时目录** | 每个会话在**自己的工作目录**下得到 `_tmp/<会话标题>/`;换工作区也各自生效 |
22
+ | **改名同步** | 会话标题就是任务名;改名时目录**自动重命名**(连同里面的文件) |
23
+ | **重启可认领** | 目录内 `.dsh-task.json` 记录 session id;重启后靠标记文件对上 |
24
+ | **取路径工具** | `task_tmpdir` 返回**当时**的准确路径(自动创建、跟随改名),可选 `sub` 建子目录 |
25
+ | **长期落点审批** | `longterm_approve` 登记"本次会话已获用户同意的长期目录",登记后该目录可写 |
26
+ | **工作区拦截** | guard 覆盖 `write`/`edit` + `pwsh`/`bash`:未审批的 `_tmp` 之外落点一律拒绝 |
27
+ | **孤儿目录清理** | 会话被删除后,临时目录保留 7 天再删;会话还在的目录永不删 |
28
+ | **手动清理** | `tmp_cleanup` 立刻跑一轮清理(`dryRun: true` 只报告) |
29
+
30
+ ## 配置(cordis.patch.yml 的 config)
31
+
32
+ | 字段 | 默认 | 说明 |
33
+ |---|---|---|
34
+ | `rootDirName` | `_tmp` | 临时目录根名(相对会话工作目录) |
35
+ | `includeSubagents` | `false` | 是否给子代理会话也建目录 |
36
+ | `maxNameLength` | `60` | 目录名最大长度 |
37
+ | `orphanCleanupDays` | `7` | 会话被删除后保留多少天再清理;`0` = 关闭清理 |
38
+ | `cleanupIntervalHours` | `24` | 清理扫描间隔(小时) |
39
+ | `cleanupDryRun` | `false` | 只打印"会标记/会删哪些"、不动手 |
40
+ | `guardWorkspaceRoot` | `true` | v1 临时文件规则总开关(根目录临时命名、`_tmp/` 根文件) |
41
+ | `requireApprovalOutsideTmp` | `true` | v0.5 长期落点审批总开关:`_tmp` 之外的写入必须有已登记目录 |
42
+ | `allowRootPatterns` | `['dsh-*']` | 无需审批的根目录名(glob,`*`/`?`) |
43
+ | `allowRootFiles` | `['.dsh-standing-rules.md']` | 无需审批的工作区根文件 |
44
+ | `commandGuard` | `deny` | pwsh/bash 命令守卫:`deny` / `warn`(只记日志)/ `off` |
45
+
46
+ ## 长期文件审批流程
47
+
48
+ 1. 模型判断某文件需要长期保存,且不在任务指定位置;
49
+ 2. 模型调用 `ask_user_question` 给用户选择题(A 指定目录 / B 新建归档 / C 临时 `_tmp`);
50
+ 3. 用户选长期 + 给路径 → 模型调 `longterm_approve({ path, reason, basis })` 登记;
51
+ 4. 之后 `write`/`edit`/`pwsh` 才能写该目录;用户否定 → 模型改用 `task_tmpdir` 写 `_tmp`。
52
+
53
+ `longterm_approve` 的登记是**按会话内存保存**:Host 重启或会话结束即清空,需要时重新审批(不会把"同意"永久写死)。
54
+
55
+ ## guard 行为边界
56
+
57
+ - `write`/`edit`:目标在工作区外 → 放行;在 `_tmp/` 下 → 放行;在已批准目录下 → 放行;在 `allowRootPatterns`/`allowRootFiles` 命中处 → 放行;其余一律拒绝。
58
+ - 工作区根**任何新文件/新文件夹**(除白名单)→ 拒绝。
59
+ - `pwsh`/`bash`:只做启发式——命令含创建动词、且命令里出现**尚不存在**的工作区绝对路径时拒绝;已在的路径(`Copy-Item` 源、正在编辑的文件)不拦;变量拼接/脚本内部/相对路径解析不了就放行(fail-open,**不是安全边界**)。
60
+ - 拦不到:脚本内部 `node -e`/`python` 写盘、外部程序、GUI 操作、绕过工具的直接 fs 调用。
61
+ - 只在**会话工作目录 = 已注册工作区根**时生效;会话 `cd` 到子目录(或子代理以插件目录为 cwd)时不会把项目顶层文件当成"工作区根新建条目"。
62
+ - guard 是**全局**的:队友/子代理/定时任务会话同样受约束。
63
+
64
+ ## 自动清理规则(安全边界)
65
+
66
+ - 判定依据是「会话是否还存在」:先看活跃会话(`ctx.sessions`),再看已持久化会话(`sessionPersistence.list()`,取不到时回退扫描 `~/.dsh/sessions`)。
67
+ - 会话还在 → 目录保留;会话已删除 → 首次扫描标记孤儿(`orphanedAt`),满 `orphanCleanupDays` 天后下一次扫描删除。
68
+ - **只处理带本插件标记的目录**(`.dsh-task.json` 且含 sessionId);手工放进 `_tmp` 的其他目录不碰。
69
+ - 启动后约 60 秒跑第一次,之后按 `cleanupIntervalHours` 周期跑;`orphanCleanupDays: 0` 关闭清理。
70
+ - 删除是**整目录递归删除**,不备份;想先观察就把 `cleanupDryRun: true` 开着跑一轮。
71
+
72
+ ## 开发
73
+
74
+ ```powershell
75
+ node --check index.js
76
+ node test/guard-v2.mjs # 22 条纯函数用例
77
+ ```
78
+
79
+ v0.5 变更(2026-11-07):新增长期落点审批(`longterm_approve` + guard v2),覆盖 pwsh/bash 命令;修复 v1 只拦"临时命名文件"导致根目录被会话自建文件夹的问题。
@@ -0,0 +1,22 @@
1
+ - insert:
2
+ - id: session-task-tmpdir
3
+ name: '@local/dsh-session-tmpdir'
4
+ config:
5
+ rootDirName: _tmp
6
+ includeSubagents: false
7
+ maxNameLength: 60
8
+ # 自动清理:会话被删除后,其任务临时目录保留 N 天再删(0 = 关闭)
9
+ orphanCleanupDays: 7
10
+ cleanupIntervalHours: 24
11
+ # 先试运行观察(只打印不删)时设为 true
12
+ cleanupDryRun: false
13
+ # v0.5:除 _tmp 外的长期落点必须经用户同意(longterm_approve)才能写
14
+ requireApprovalOutsideTmp: true
15
+ # 无需审批即可写的根目录名(支持 * ? 通配):插件源码目录
16
+ allowRootPatterns:
17
+ - dsh-*
18
+ # 无需审批即可写的工作区根文件
19
+ allowRootFiles:
20
+ - .dsh-standing-rules.md
21
+ # pwsh/bash 命令守卫:deny(拦截)| warn(只记日志)| off(关闭)
22
+ commandGuard: deny
package/icon.svg ADDED
@@ -0,0 +1,13 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96" width="96" height="96" role="img" aria-label="Task temp folder">
2
+ <defs>
3
+ <linearGradient id="folder" x1="0" y1="0" x2="0" y2="1">
4
+ <stop offset="0" stop-color="#4d7cfe"/>
5
+ <stop offset="1" stop-color="#2f56d6"/>
6
+ </linearGradient>
7
+ </defs>
8
+ <path d="M10 26a6 6 0 0 1 6-6h20l7 8h31a6 6 0 0 1 6 6v34a6 6 0 0 1-6 6H16a6 6 0 0 1-6-6z" fill="url(#folder)"/>
9
+ <path d="M10 38h76v30a6 6 0 0 1-6 6H16a6 6 0 0 1-6-6z" fill="#5c8cff" opacity=".55"/>
10
+ <circle cx="62" cy="58" r="13" fill="#0f1730"/>
11
+ <path d="M62 50v9l6 4" stroke="#ffffff" stroke-width="4" stroke-linecap="round" fill="none"/>
12
+ <text x="30" y="66" font-family="Segoe UI, Arial, sans-serif" font-size="20" font-weight="700" fill="#ffffff">_tmp</text>
13
+ </svg>
package/index.js ADDED
@@ -0,0 +1,1056 @@
1
+ import { existsSync, statSync } from 'node:fs'
2
+ import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
3
+ import { homedir } from 'node:os'
4
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
5
+
6
+ /**
7
+ * Per-session task temp folder + orphan cleanup + workspace-root long-term guard.
8
+ *
9
+ * Every session gets `<working directory>/<rootDirName>/<sanitized session title>/`.
10
+ * The folder is created on `session/created` when a title already exists, and on the
11
+ * first `session/title` commit. Later title changes (user rename or a regenerated
12
+ * auto title) rename the folder in place. A marker file inside the folder records the
13
+ * owning session id, so the mapping survives plugin/Host restarts without a state file.
14
+ *
15
+ * Two kinds of writes are governed (v0.5):
16
+ * 1. scratch artifacts (anything under `<rootDirName>/`) — always allowed, never asks;
17
+ * 2. long-term artifacts (everything else inside the workspace) — only allowed under a
18
+ * directory the session has registered through `longterm_approve`, which the model
19
+ * may only call after the user picked a location (a multiple-choice question) or
20
+ * after the task itself named that location. Root-level new files are always denied
21
+ * unless explicitly allow-listed (config `allowRootFiles`).
22
+ * This makes "silently invent a root folder for long-term docs" impossible: the write is
23
+ * refused and the model is told to ask the user first, and to fall back to the temp
24
+ * folder when the user declines.
25
+ *
26
+ * Cleanup (default: 7 days after the owning session is deleted):
27
+ * - once a day every registered workspace's `<rootDirName>` is scanned;
28
+ * - a folder whose session still exists (live or persisted) is always kept;
29
+ * - a folder whose session is gone is stamped `orphanedAt` on first sight;
30
+ * - once `orphanedAt` is older than `orphanCleanupDays`, the folder is deleted.
31
+ * Folders without our marker are never touched.
32
+ */
33
+
34
+ const MARKER_FILE = '.dsh-task.json'
35
+ const DEFAULT_ROOT = '_tmp'
36
+ const DEFAULT_MAX_NAME = 60
37
+ const DEFAULT_ORPHAN_DAYS = 7
38
+ const DEFAULT_CLEANUP_HOURS = 24
39
+ const STARTUP_CLEANUP_DELAY_MS = 60_000
40
+ const FALLBACK_PREFIX = 'session-'
41
+ const DAY_MS = 86_400_000
42
+ /** Tool names whose `file_path` argument creates or overwrites a file. */
43
+ const WRITE_TOOL_NAMES = new Set(['write', 'edit'])
44
+ /** Tool names that run a shell command (their write targets must be parsed from text). */
45
+ const SHELL_TOOL_NAMES = new Set(['pwsh', 'bash', 'shell', 'terminal'])
46
+ /** File names that are scratch artifacts wherever they land. */
47
+ const TEMP_FILE_PATTERNS = [/^_tmp/i, /^tmp_/i, /\.tmp$/i, /\.temp$/i, /\.part$/i, /^~\$/]
48
+ const DEFAULT_ALLOW_ROOT_PATTERNS = ['dsh-*']
49
+ const DEFAULT_ALLOW_ROOT_FILES = ['.dsh-standing-rules.md']
50
+ const DEFAULT_COMMAND_GUARD = 'deny'
51
+ /** Command text that can create a directory/file; used before scanning for paths. */
52
+ const CREATE_VERB_PATTERN =
53
+ /\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)\b/i
54
+ /** Redirection target such as `> "D:\x\y.txt"` or `2>> log.txt`. */
55
+ const REDIRECT_PATTERN = /(?:^|[\s;&|])(?:\d?>|>>)\s*(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/
56
+ /** Windows absolute path tokens inside a command string. */
57
+ const ABS_PATH_PATTERN = /([A-Za-z]:[\\/][^\s'"`,;|&)}\]>]+)/g
58
+
59
+ export const name = 'session-task-tmpdir'
60
+
61
+ export const inject = ['sessions', 'sessionTitle', 'workingDirectory', 'systemPrompt', 'tools']
62
+
63
+ /** Strip characters that are illegal in Windows/POSIX directory names and bound the length. */
64
+ export function sanitizeTitle(raw, maxLength = DEFAULT_MAX_NAME) {
65
+ let text = String(raw ?? '')
66
+ .normalize('NFC')
67
+ // eslint-disable-next-line no-control-regex
68
+ .replace(/[\\/:*?"<>|\u0000-\u001f]+/g, '-')
69
+ .replace(/\s+/g, ' ')
70
+ .trim()
71
+ // Windows: names may not end with a dot or space
72
+ text = text.replace(/^[.\s]+|[.\s]+$/g, '')
73
+ if (!text) return ''
74
+ if (text.length > maxLength) text = text.slice(0, maxLength).trim()
75
+ text = text.replace(/^[.\s]+|[.\s]+$/g, '')
76
+ return text === '.' || text === '..' ? '' : text
77
+ }
78
+
79
+ function readConfig(config) {
80
+ const c = config && typeof config === 'object' ? config : {}
81
+ const rootDirName = typeof c.rootDirName === 'string' && c.rootDirName.trim() ? c.rootDirName.trim() : DEFAULT_ROOT
82
+ const includeSubagents = c.includeSubagents === true
83
+ const maxNameLength = Number.isInteger(c.maxNameLength) && c.maxNameLength > 0 ? c.maxNameLength : DEFAULT_MAX_NAME
84
+ const orphanCleanupDays = Number.isFinite(c.orphanCleanupDays) && c.orphanCleanupDays >= 0 ? c.orphanCleanupDays : DEFAULT_ORPHAN_DAYS
85
+ const cleanupIntervalHours = Number.isFinite(c.cleanupIntervalHours) && c.cleanupIntervalHours >= 1 ? c.cleanupIntervalHours : DEFAULT_CLEANUP_HOURS
86
+ const cleanupDryRun = c.cleanupDryRun === true
87
+ const guardWorkspaceRoot = c.guardWorkspaceRoot !== false
88
+ const requireApprovalOutsideTmp = c.requireApprovalOutsideTmp !== false
89
+ const allowRootPatterns = toStringList(c.allowRootPatterns, DEFAULT_ALLOW_ROOT_PATTERNS)
90
+ const allowRootFiles = toStringList(c.allowRootFiles, DEFAULT_ALLOW_ROOT_FILES)
91
+ const commandGuard = ['deny', 'warn', 'off'].includes(c.commandGuard) ? c.commandGuard : DEFAULT_COMMAND_GUARD
92
+ return {
93
+ rootDirName,
94
+ includeSubagents,
95
+ maxNameLength,
96
+ orphanCleanupDays,
97
+ cleanupIntervalHours,
98
+ cleanupDryRun,
99
+ guardWorkspaceRoot,
100
+ requireApprovalOutsideTmp,
101
+ allowRootPatterns,
102
+ allowRootFiles,
103
+ commandGuard,
104
+ }
105
+ }
106
+
107
+ /** Accept a string or an array of strings as a config list, falling back to `fallback`. */
108
+ function toStringList(value, fallback) {
109
+ if (typeof value === 'string' && value.trim()) return [value.trim()]
110
+ if (Array.isArray(value)) {
111
+ const list = value.filter((item) => typeof item === 'string' && item.trim()).map((item) => item.trim())
112
+ if (list.length > 0) return list
113
+ }
114
+ return [...fallback]
115
+ }
116
+
117
+ /** Windows path comparison: case-insensitive, separator-normalized. */
118
+ function samePath(a, b) {
119
+ if (typeof a !== 'string' || typeof b !== 'string') return false
120
+ const normalize = (value) => resolve(value).replace(/[\\/]+$/, '').toLowerCase()
121
+ return normalize(a) === normalize(b)
122
+ }
123
+
124
+ /**
125
+ * Reject scratch-file writes that land in the wrong place:
126
+ * temp-looking names directly in the working-directory root, or any file directly
127
+ * under `<cwd>/<rootDirName>/` instead of a session subfolder.
128
+ *
129
+ * @param {string} targetPath the write/edit `file_path` argument (absolute or relative to cwd)
130
+ * @param {string} cwd the session working directory
131
+ * @param {string} [rootDirName] temp root name (default `_tmp`)
132
+ * @returns {string | undefined} denial reason for the tool guard, or undefined to allow
133
+ */
134
+ export function workspaceRootGuardReason(targetPath, cwd, rootDirName = DEFAULT_ROOT) {
135
+ if (typeof targetPath !== 'string' || targetPath.trim() === '') return undefined
136
+ if (typeof cwd !== 'string' || cwd.trim() === '') return undefined
137
+ let abs
138
+ try {
139
+ abs = isAbsolute(targetPath) ? targetPath : resolve(cwd, targetPath)
140
+ } catch {
141
+ return undefined
142
+ }
143
+ const name = basename(abs)
144
+ if (!name) return undefined
145
+ if (samePath(dirname(abs), cwd) && TEMP_FILE_PATTERNS.some((pattern) => pattern.test(name))) {
146
+ return (
147
+ `工作区根目录不能放临时文件(${name})。请先调用 task_tmpdir 获取 ` +
148
+ `${rootDirName}/<会话标题>/ 的准确路径,把临时文件写进那个目录。`
149
+ )
150
+ }
151
+ if (samePath(dirname(abs), join(cwd, rootDirName))) {
152
+ return (
153
+ `${rootDirName}/ 根目录不能直接放文件(${name})。请先调用 task_tmpdir,` +
154
+ `把文件写入 ${rootDirName}/<会话标题>/ 子目录。`
155
+ )
156
+ }
157
+ return undefined
158
+ }
159
+
160
+ // ── long-term destination guard (v0.5) ─────────────────────────────────────────
161
+
162
+ /** Lower-cased, separator-normalized path used for comparisons. */
163
+ function normalizeForCompare(target) {
164
+ return resolve(target).replace(/[\\/]+$/, '').toLowerCase()
165
+ }
166
+
167
+ /** True when `child` is `parent` or lives inside it (case-insensitive on Windows). */
168
+ export function pathInside(parent, child) {
169
+ if (typeof parent !== 'string' || typeof child !== 'string') return false
170
+ if (!parent.trim() || !child.trim()) return false
171
+ const p = normalizeForCompare(parent)
172
+ const c = normalizeForCompare(child)
173
+ return c === p || c.startsWith(`${p}\\`)
174
+ }
175
+
176
+ /** First path segment of `abs` relative to `cwd`, or undefined when not inside `cwd`. */
177
+ export function firstSegmentUnder(cwd, abs) {
178
+ if (typeof cwd !== 'string' || typeof abs !== 'string') return undefined
179
+ const base = resolve(cwd)
180
+ const target = resolve(abs)
181
+ if (!(normalizeForCompare(base) === normalizeForCompare(target) || pathInside(base, target))) return undefined
182
+ if (normalizeForCompare(base) === normalizeForCompare(target)) return ''
183
+ const rest = target.slice(base.replace(/[\\/]+$/, '').length).replace(/^[\\/]+/, '')
184
+ const [first] = rest.split(/[\\/]+/).filter(Boolean)
185
+ return first ?? ''
186
+ }
187
+
188
+ /** Simple case-insensitive glob matcher (`*` and `?` only). */
189
+ export function globMatch(name, patterns) {
190
+ const text = String(name ?? '')
191
+ for (const raw of patterns ?? []) {
192
+ const pattern = String(raw ?? '').trim()
193
+ if (!pattern) continue
194
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
195
+ try {
196
+ if (new RegExp(`^${escaped}$`, 'i').test(text)) return true
197
+ } catch {
198
+ // an unusable pattern never matches
199
+ }
200
+ }
201
+ return false
202
+ }
203
+
204
+ /**
205
+ * Decide whether a `write`/`edit` target outside the temp root may be written.
206
+ *
207
+ * Rules (v0.5):
208
+ * - under `<cwd>/<rootDirName>/` → allowed (scratch);
209
+ * - under an approved long-term prefix → allowed (session registered it via longterm_approve);
210
+ * - root-level file → allowed only when explicitly allow-listed;
211
+ * - first segment matching allowRootPatterns → allowed (plugin source trees by default);
212
+ * - anything else → denied with the "ask the user first" protocol.
213
+ *
214
+ * @returns {string | undefined} denial reason, or undefined to allow
215
+ */
216
+ export function longtermGuardReason(targetPath, cwd, options = {}) {
217
+ const {
218
+ rootDirName = DEFAULT_ROOT,
219
+ allowRootPatterns = DEFAULT_ALLOW_ROOT_PATTERNS,
220
+ allowRootFiles = DEFAULT_ALLOW_ROOT_FILES,
221
+ approvedPrefixes = [],
222
+ requireApprovalOutsideTmp = true,
223
+ } = options
224
+ if (!requireApprovalOutsideTmp) return undefined
225
+ if (typeof targetPath !== 'string' || targetPath.trim() === '') return undefined
226
+ if (typeof cwd !== 'string' || cwd.trim() === '') return undefined
227
+ let abs
228
+ try {
229
+ abs = isAbsolute(targetPath) ? targetPath : resolve(cwd, targetPath)
230
+ } catch {
231
+ return undefined
232
+ }
233
+ const base = resolve(cwd)
234
+ if (!pathInside(base, abs)) return undefined
235
+ const tmpRoot = join(base, rootDirName)
236
+ if (pathInside(tmpRoot, abs)) return undefined
237
+ if (approvedPrefixes.some((prefix) => pathInside(prefix, abs))) return undefined
238
+ if (samePath(dirname(abs), base)) {
239
+ const name = basename(abs)
240
+ if (allowRootFiles.some((entry) => entry.toLowerCase() === name.toLowerCase())) return undefined
241
+ if (globMatch(name, allowRootPatterns)) return undefined
242
+ return (
243
+ `工作区根目录不能新建/修改条目(${name})。若这份内容需要长期保存:先用 ask_user_question 征求用户意见,` +
244
+ `用户同意后用 longterm_approve 登记用户指定的目录再写;用户不同意或属于临时产物 → 用 task_tmpdir 写到 ` +
245
+ `${rootDirName}/<会话标题>/。`
246
+ )
247
+ }
248
+ const first = firstSegmentUnder(base, abs)
249
+ if (!first) return undefined
250
+ if (globMatch(first, allowRootPatterns)) return undefined
251
+ return (
252
+ `「${first}」不在本次会话已批准的长期落点里。若这份内容需要长期保存:先用 ask_user_question 征求用户意见,` +
253
+ `用户同意后调用 longterm_approve 登记用户指定的目录再写;用户不同意或属于临时产物 → 用 task_tmpdir 写到 ` +
254
+ `${rootDirName}/<会话标题>/。`
255
+ )
256
+ }
257
+
258
+ /**
259
+ * Best-effort guard for shell tools: when a command may create something, scan its
260
+ * literal absolute Windows paths. Any not-yet-existing path inside the workspace that is
261
+ * neither scratch nor approved is denied. Paths that already exist are left alone (they are
262
+ * usually sources for Copy-Item or files being edited) — this keeps false positives low.
263
+ *
264
+ * @returns {string | undefined} denial reason, or undefined to allow
265
+ */
266
+ export function longtermCommandGuardReason(command, workspaceRoot, options = {}) {
267
+ const {
268
+ rootDirName = DEFAULT_ROOT,
269
+ allowRootPatterns = DEFAULT_ALLOW_ROOT_PATTERNS,
270
+ allowRootFiles = DEFAULT_ALLOW_ROOT_FILES,
271
+ approvedPrefixes = [],
272
+ requireApprovalOutsideTmp = true,
273
+ baseDir,
274
+ pathExists = (target) => existsSync(target),
275
+ } = options
276
+ if (!requireApprovalOutsideTmp) return undefined
277
+ if (typeof command !== 'string' || command.trim() === '') return undefined
278
+ if (typeof workspaceRoot !== 'string' || workspaceRoot.trim() === '') return undefined
279
+ if (!CREATE_VERB_PATTERN.test(command)) return undefined
280
+ const base = resolve(workspaceRoot)
281
+ const resolveBase = typeof baseDir === 'string' && baseDir.trim() ? resolve(baseDir) : base
282
+ const tokens = new Set()
283
+ const redirect = command.match(REDIRECT_PATTERN)
284
+ if (redirect) tokens.add(redirect[1] ?? redirect[2] ?? redirect[3])
285
+ for (const match of command.matchAll(ABS_PATH_PATTERN)) tokens.add(match[1])
286
+ for (const raw of tokens) {
287
+ if (!raw) continue
288
+ const cleaned = String(raw).replace(/["'`]+$/, '')
289
+ let abs
290
+ try {
291
+ abs = isAbsolute(cleaned) ? cleaned : resolve(resolveBase, cleaned)
292
+ } catch {
293
+ continue
294
+ }
295
+ if (!pathInside(base, abs)) continue
296
+ const tmpRoot = join(base, rootDirName)
297
+ if (pathInside(tmpRoot, abs)) continue
298
+ if (approvedPrefixes.some((prefix) => pathInside(prefix, abs))) continue
299
+ if (samePath(dirname(abs), base)) {
300
+ const name = basename(abs)
301
+ if (allowRootFiles.some((entry) => entry.toLowerCase() === name.toLowerCase())) continue
302
+ if (globMatch(name, allowRootPatterns)) continue
303
+ if (pathExists(abs)) continue
304
+ return (
305
+ `命令会新建工作区根目录条目「${name}」(${abs})。若需要长期保存:先用 ask_user_question 征求用户意见,` +
306
+ `同意后 longterm_approve 登记目录再执行;临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
307
+ )
308
+ }
309
+ const first = firstSegmentUnder(base, abs)
310
+ if (first && globMatch(first, allowRootPatterns)) continue
311
+ if (pathExists(abs)) continue
312
+ return (
313
+ `命令会新建工作区里的「${first || basename(abs)}」(${abs}),它不在本次会话已批准的长期落点里。` +
314
+ `若需要长期保存:先用 ask_user_question 征求用户意见,同意后 longterm_approve 登记目录再执行;` +
315
+ `临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
316
+ )
317
+ }
318
+ return undefined
319
+ }
320
+
321
+ async function readMarker(dir) {
322
+ try {
323
+ return JSON.parse(await readFile(join(dir, MARKER_FILE), 'utf8'))
324
+ } catch {
325
+ return undefined
326
+ }
327
+ }
328
+
329
+ async function writeMarker(dir, sessionId, title, orphanedAt) {
330
+ const payload = { sessionId: String(sessionId), title: title ?? '', updatedAt: Date.now() }
331
+ if (Number.isFinite(orphanedAt) && orphanedAt > 0) payload.orphanedAt = orphanedAt
332
+ try {
333
+ await writeFile(join(dir, MARKER_FILE), JSON.stringify(payload, null, 2), 'utf8')
334
+ } catch {
335
+ // marker is best-effort; the folder still works without it
336
+ }
337
+ }
338
+
339
+ /**
340
+ * Delete marker-owned task folders whose owning session has been gone for `orphanDays`.
341
+ *
342
+ * @param {object} options
343
+ * @param {Iterable<string>} options.roots workspace directories to scan
344
+ * @param {string} [options.rootDirName] temp root name (default `_tmp`)
345
+ * @param {number} options.orphanDays days after session deletion before removal (0 disables)
346
+ * @param {boolean} [options.dryRun] report only, write/delete nothing
347
+ * @param {Iterable<string>} [options.liveSessionIds] currently live sessions (never removed)
348
+ * @param {Iterable<string>} [options.existingSessionIds] persisted sessions (never removed)
349
+ * @param {number} [options.now] timestamp override (tests)
350
+ * @param {(message: string) => void} [options.log] progress logger
351
+ * @returns {Promise<object>} report
352
+ */
353
+ export async function cleanupOrphanedTempDirs({
354
+ roots,
355
+ rootDirName = DEFAULT_ROOT,
356
+ orphanDays,
357
+ dryRun = false,
358
+ liveSessionIds = [],
359
+ existingSessionIds = [],
360
+ now = Date.now(),
361
+ log = () => {},
362
+ }) {
363
+ const report = {
364
+ dryRun,
365
+ cutoff: now - orphanDays * DAY_MS,
366
+ roots: [],
367
+ markedOrphaned: [],
368
+ deleted: [],
369
+ kept: { live: 0, alive: 0, unmarked: 0, waiting: 0, error: 0 },
370
+ }
371
+ if (!(orphanDays > 0)) return report
372
+ const live = new Set([...liveSessionIds].map((id) => String(id)))
373
+ const known = new Set([...existingSessionIds].map((id) => String(id)))
374
+ for (const id of live) known.add(id)
375
+ const uniqueRoots = new Set([...roots].filter((root) => typeof root === 'string' && root.trim() !== ''))
376
+
377
+ for (const root of uniqueRoots) {
378
+ const tmpRoot = join(root, rootDirName)
379
+ let entries
380
+ try {
381
+ entries = await readdir(tmpRoot, { withFileTypes: true })
382
+ } catch {
383
+ continue
384
+ }
385
+ report.roots.push(tmpRoot)
386
+ for (const entry of entries) {
387
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue
388
+ const dir = join(tmpRoot, entry.name)
389
+ try {
390
+ const marker = await readMarker(dir)
391
+ if (!marker) {
392
+ report.kept.unmarked += 1
393
+ continue
394
+ }
395
+ const sessionId = String(marker.sessionId ?? '')
396
+ if (!sessionId) {
397
+ report.kept.unmarked += 1
398
+ continue
399
+ }
400
+ if (live.has(sessionId)) {
401
+ report.kept.live += 1
402
+ continue
403
+ }
404
+ if (known.has(sessionId)) {
405
+ report.kept.alive += 1
406
+ if (Number(marker.orphanedAt) > 0 && !dryRun) await writeMarker(dir, sessionId, marker.title, undefined)
407
+ continue
408
+ }
409
+ // Owning session no longer exists.
410
+ const orphanedAt = Number(marker.orphanedAt) || 0
411
+ if (orphanedAt <= 0) {
412
+ report.markedOrphaned.push(dir)
413
+ if (dryRun) {
414
+ report.kept.waiting += 1
415
+ log(`[dry-run] would mark orphaned ${dir}`)
416
+ } else {
417
+ await writeMarker(dir, sessionId, marker.title, now)
418
+ log(`marked orphaned ${dir}`)
419
+ }
420
+ continue
421
+ }
422
+ if (now - orphanedAt < orphanDays * DAY_MS) {
423
+ report.kept.waiting += 1
424
+ continue
425
+ }
426
+ if (dryRun) {
427
+ report.deleted.push({ path: dir, dryRun: true })
428
+ log(`[dry-run] would delete ${dir}`)
429
+ continue
430
+ }
431
+ await rm(dir, { recursive: true, force: true })
432
+ report.deleted.push({ path: dir })
433
+ log(`deleted ${dir}`)
434
+ } catch {
435
+ report.kept.error += 1
436
+ }
437
+ }
438
+ }
439
+ return report
440
+ }
441
+
442
+ /** Best-effort fallback: collect session ids from the persisted session tree. */
443
+ async function scanPersistedSessionIds() {
444
+ const ids = new Set()
445
+ const home = process.env.DSH_HOME && process.env.DSH_HOME.trim() ? process.env.DSH_HOME.trim() : join(homedir(), '.dsh')
446
+ const roots = [join(home, 'sessions'), join(home, '_archived-sessions')]
447
+ const idPattern = /^(?:session-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
448
+ for (const root of roots) {
449
+ let workspaces
450
+ try {
451
+ workspaces = await readdir(root, { withFileTypes: true })
452
+ } catch {
453
+ continue
454
+ }
455
+ for (const workspace of workspaces) {
456
+ if (!workspace.isDirectory()) continue
457
+ const workspaceDir = join(root, workspace.name)
458
+ // Session directories live one level below; also cover a flat layout.
459
+ if (idPattern.test(workspace.name)) {
460
+ ids.add(workspace.name.replace(/^session-/, ''))
461
+ continue
462
+ }
463
+ let sessions
464
+ try {
465
+ sessions = await readdir(workspaceDir, { withFileTypes: true })
466
+ } catch {
467
+ continue
468
+ }
469
+ for (const session of sessions) {
470
+ if (!session.isDirectory()) continue
471
+ if (idPattern.test(session.name)) ids.add(session.name.replace(/^session-/, ''))
472
+ }
473
+ }
474
+ }
475
+ return ids
476
+ }
477
+
478
+ export function apply(ctx, config) {
479
+ const {
480
+ rootDirName,
481
+ includeSubagents,
482
+ maxNameLength,
483
+ orphanCleanupDays,
484
+ cleanupIntervalHours,
485
+ cleanupDryRun,
486
+ guardWorkspaceRoot,
487
+ requireApprovalOutsideTmp,
488
+ allowRootPatterns,
489
+ allowRootFiles,
490
+ commandGuard,
491
+ } = readConfig(config)
492
+ const queues = new Map()
493
+ /** sessionId → approved long-term prefixes ({ prefix, reason, basis, approvedAt }[]). */
494
+ const approvals = new Map()
495
+ let sessionPersistence
496
+ let workspaceRegistry
497
+ try {
498
+ ctx.inject(['sessionPersistence'], (scoped) => {
499
+ sessionPersistence = scoped.sessionPersistence
500
+ })
501
+ } catch {
502
+ // fallback: the persisted session tree is scanned directly
503
+ }
504
+ try {
505
+ ctx.inject(['workspaceRegistry'], (scoped) => {
506
+ workspaceRegistry = scoped.workspaceRegistry
507
+ })
508
+ } catch {
509
+ // workspaceRegistry is optional; live sessions and the default directory still cover roots
510
+ }
511
+
512
+ const cwdOf = (session) => {
513
+ try {
514
+ const dir = ctx.workingDirectory.get(session)
515
+ if (typeof dir === 'string' && dir) return dir
516
+ } catch {
517
+ // fall through to the header value
518
+ }
519
+ const headerCwd = session?.header?.cwd
520
+ return typeof headerCwd === 'string' && headerCwd ? headerCwd : undefined
521
+ }
522
+
523
+ const titleOf = (session) => {
524
+ try {
525
+ const snapshot = ctx.sessionTitle.get(session)
526
+ if (snapshot?.title) return snapshot.title
527
+ } catch {
528
+ // title provider may be absent or the session may be detached
529
+ }
530
+ return undefined
531
+ }
532
+
533
+ const isRelevant = (session) => includeSubagents || session?.header?.origin !== 'subagent'
534
+
535
+ /**
536
+ * The root-entry guard only makes sense when the session is working at a workspace
537
+ * root. A session `cd`-ed into a subfolder (or a subagent started in a plugin dir)
538
+ * must not have its project files treated as "new workspace-root entries".
539
+ */
540
+ function isProtectedRoot(cwd) {
541
+ let workspaces = []
542
+ try {
543
+ workspaces = workspaceRegistry?.list() ?? []
544
+ } catch {
545
+ workspaces = []
546
+ }
547
+ if (workspaces.length > 0) return workspaces.some((workspace) => samePath(workspace?.path, cwd))
548
+ // Registry not ready: keep the historical strict behavior, default directory still counts.
549
+ try {
550
+ const defaultDir = ctx.workingDirectory.defaultDirectory
551
+ if (typeof defaultDir === 'string' && defaultDir) return samePath(defaultDir, cwd)
552
+ } catch {
553
+ // no default directory
554
+ }
555
+ return true
556
+ }
557
+
558
+ const baseDir = (cwd) => join(cwd, rootDirName)
559
+
560
+ // ── long-term approvals (per live session, in memory) ──────────────────────
561
+ const sessionKey = (session) => {
562
+ try {
563
+ return session?.id ? String(session.id) : ''
564
+ } catch {
565
+ return ''
566
+ }
567
+ }
568
+
569
+ function approvedPrefixesFor(session) {
570
+ const id = sessionKey(session)
571
+ const list = id ? approvals.get(id) : undefined
572
+ return list ? list.map((entry) => entry.prefix) : []
573
+ }
574
+
575
+ function registerApproval(session, prefix, { reason, basis }) {
576
+ const id = sessionKey(session)
577
+ if (!id) throw new Error('longterm_approve: session is unavailable')
578
+ const list = approvals.get(id) ?? []
579
+ const normalized = resolve(prefix)
580
+ if (!list.some((entry) => normalizeForCompare(entry.prefix) === normalizeForCompare(normalized))) {
581
+ list.push({ prefix: normalized, reason: reason ?? '', basis: basis ?? 'user_confirmed', approvedAt: Date.now() })
582
+ approvals.set(id, list)
583
+ console.info(`[session-task-tmpdir] longterm approved ${normalized} (session ${id})`)
584
+ }
585
+ return list
586
+ }
587
+
588
+ async function isDir(path) {
589
+ try {
590
+ return (await stat(path)).isDirectory()
591
+ } catch {
592
+ return false
593
+ }
594
+ }
595
+
596
+ async function findOwnedDir(cwd, sessionId) {
597
+ const root = baseDir(cwd)
598
+ let entries
599
+ try {
600
+ entries = await readdir(root, { withFileTypes: true })
601
+ } catch {
602
+ return undefined
603
+ }
604
+ for (const entry of entries) {
605
+ if (!entry.isDirectory()) continue
606
+ const dir = join(root, entry.name)
607
+ const marker = await readMarker(dir)
608
+ if (marker && String(marker.sessionId) === String(sessionId)) return dir
609
+ }
610
+ return undefined
611
+ }
612
+
613
+ /**
614
+ * Pick a target path for `name`: reuse the folder owned by this session, adopt an
615
+ * empty unowned folder (removing it first when `removeEmpty` prepares a rename),
616
+ * otherwise append a numeric suffix.
617
+ */
618
+ async function chooseTarget(root, name, sessionId, { removeEmpty = false } = {}) {
619
+ let target = join(root, name)
620
+ let n = 2
621
+ for (;;) {
622
+ if (!(await isDir(target))) return target
623
+ const marker = await readMarker(target)
624
+ if (marker && sessionId !== undefined && String(marker.sessionId) === String(sessionId)) return target
625
+ const entries = await readdir(target).catch(() => [])
626
+ if (!marker && entries.length === 0) {
627
+ if (!removeEmpty) return target
628
+ await rm(target, { recursive: true, force: true }).catch(() => {})
629
+ return target
630
+ }
631
+ target = join(root, `${name} (${n++})`)
632
+ }
633
+ }
634
+
635
+ async function createDir(session, sub) {
636
+ const cwd = cwdOf(session)
637
+ if (!cwd) throw new Error('session working directory is unavailable')
638
+ const title = titleOf(session)
639
+ const name = sanitizeTitle(title, maxNameLength) || `${FALLBACK_PREFIX}${String(session.id).slice(0, 8)}`
640
+ const root = baseDir(cwd)
641
+ await mkdir(root, { recursive: true })
642
+ // Reuse the folder this session already owns (e.g. a `sub` call after the first call)
643
+ const owned = await findOwnedDir(cwd, session.id)
644
+ const target = owned ?? (await chooseTarget(root, name, session.id))
645
+ await mkdir(target, { recursive: true })
646
+ await writeMarker(target, session.id, title ?? '')
647
+ const path = sub ? join(target, sanitizeTitle(sub, maxNameLength) || 'sub') : target
648
+ if (sub) await mkdir(path, { recursive: true })
649
+ return { path, title: title ?? '' }
650
+ }
651
+
652
+ async function syncDir(session) {
653
+ const cwd = cwdOf(session)
654
+ if (!cwd) return
655
+ const title = titleOf(session)
656
+ if (!title) return
657
+ const name = sanitizeTitle(title, maxNameLength)
658
+ if (!name) return
659
+ const root = baseDir(cwd)
660
+ const owned = await findOwnedDir(cwd, session.id)
661
+ if (!owned) {
662
+ await createDir(session)
663
+ return
664
+ }
665
+ if (owned === join(root, name)) {
666
+ await writeMarker(owned, session.id, title)
667
+ return
668
+ }
669
+ const target = await chooseTarget(root, name, session.id, { removeEmpty: true })
670
+ if (target === owned) return
671
+ try {
672
+ await rename(owned, target)
673
+ } catch (error) {
674
+ // A locked file can block the rename on Windows; keep the old folder and its marker.
675
+ console.warn('[session-task-tmpdir] rename failed:', error?.message ?? error)
676
+ return
677
+ }
678
+ await writeMarker(target, session.id, title)
679
+ }
680
+
681
+ function enqueue(session) {
682
+ const id = String(session.id)
683
+ const previous = queues.get(id) ?? Promise.resolve()
684
+ const next = previous
685
+ .then(() => syncDir(session))
686
+ .catch((error) => console.warn('[session-task-tmpdir] sync failed:', error?.message ?? error))
687
+ .finally(() => {
688
+ if (queues.get(id) === next) queues.delete(id)
689
+ })
690
+ queues.set(id, next)
691
+ }
692
+
693
+ // Title change (user rename and automatic title regeneration both append session/title).
694
+ ctx.effect(() =>
695
+ ctx.on('session/event', (session, event) => {
696
+ if (event?.type !== 'session/title') return
697
+ if (!session || !isRelevant(session)) return
698
+ enqueue(session)
699
+ }),
700
+ )
701
+
702
+ // A resumed session may already carry a title; materialize the folder on creation.
703
+ ctx.effect(() =>
704
+ ctx.on('session/created', (session) => {
705
+ if (!session || !isRelevant(session)) return
706
+ enqueue(session)
707
+ }),
708
+ )
709
+
710
+ // Drop per-session long-term approvals once the session is gone.
711
+ ctx.effect(() =>
712
+ ctx.on('session/disposed', (session) => {
713
+ const id = sessionKey(session)
714
+ if (id) approvals.delete(id)
715
+ }),
716
+ )
717
+
718
+ // ── orphan cleanup ─────────────────────────────────────────────────────────
719
+ let cleaning = false
720
+
721
+ async function collectPersistedSessionIds() {
722
+ if (sessionPersistence && typeof sessionPersistence.list === 'function') {
723
+ try {
724
+ const snapshots = await sessionPersistence.list()
725
+ return snapshots.map((snapshot) => String(snapshot?.header?.id ?? '')).filter(Boolean)
726
+ } catch {
727
+ // fall through to the directory scan
728
+ }
729
+ }
730
+ return [...(await scanPersistedSessionIds())]
731
+ }
732
+
733
+ async function runCleanup(trigger, { dryRun = cleanupDryRun } = {}) {
734
+ if (cleaning || !(orphanCleanupDays > 0)) return undefined
735
+ cleaning = true
736
+ try {
737
+ const roots = new Set()
738
+ try {
739
+ const defaultDir = ctx.workingDirectory.defaultDirectory
740
+ if (typeof defaultDir === 'string' && defaultDir) roots.add(defaultDir)
741
+ } catch {
742
+ /* no default directory */
743
+ }
744
+ const liveSessionIds = []
745
+ try {
746
+ for (const session of ctx.sessions.list()) {
747
+ liveSessionIds.push(String(session.id))
748
+ const dir = cwdOf(session)
749
+ if (dir) roots.add(dir)
750
+ }
751
+ } catch {
752
+ /* sessions unavailable this tick */
753
+ }
754
+ try {
755
+ for (const workspace of workspaceRegistry?.list() ?? []) {
756
+ if (workspace?.path) roots.add(workspace.path)
757
+ }
758
+ } catch {
759
+ /* registry unavailable this tick */
760
+ }
761
+ const existingSessionIds = await collectPersistedSessionIds()
762
+ const report = await cleanupOrphanedTempDirs({
763
+ roots,
764
+ rootDirName,
765
+ orphanDays: orphanCleanupDays,
766
+ dryRun,
767
+ liveSessionIds,
768
+ existingSessionIds,
769
+ log: (message) => console.info(`[session-task-tmpdir] ${message}`),
770
+ })
771
+ if (
772
+ report.deleted.length > 0 ||
773
+ report.markedOrphaned.length > 0 ||
774
+ report.kept.error > 0
775
+ ) {
776
+ console.info(
777
+ `[session-task-tmpdir] cleanup(${trigger})${report.dryRun ? ' dry-run' : ''}: ` +
778
+ `deleted ${report.deleted.length}, marked ${report.markedOrphaned.length}, ` +
779
+ `kept live ${report.kept.live} / alive ${report.kept.alive} / waiting ${report.kept.waiting} / ` +
780
+ `unmarked ${report.kept.unmarked} / errors ${report.kept.error}`,
781
+ )
782
+ }
783
+ return report
784
+ } catch (error) {
785
+ console.warn('[session-task-tmpdir] cleanup failed:', error?.message ?? error)
786
+ return undefined
787
+ } finally {
788
+ cleaning = false
789
+ }
790
+ }
791
+
792
+ if (orphanCleanupDays > 0) {
793
+ ctx.effect(() => {
794
+ const startupTimer = setTimeout(() => {
795
+ void runCleanup('startup')
796
+ }, STARTUP_CLEANUP_DELAY_MS)
797
+ const interval = setInterval(() => {
798
+ void runCleanup('interval')
799
+ }, cleanupIntervalHours * 3_600_000)
800
+ return () => {
801
+ clearTimeout(startupTimer)
802
+ clearInterval(interval)
803
+ }
804
+ }, 'session-task-tmpdir: cleanup schedule')
805
+ }
806
+
807
+ // ── prompt convention + tool ────────────────────────────────────────────────
808
+ ctx.effect(() =>
809
+ ctx.systemPrompt.context({
810
+ name: 'session-task-tmpdir',
811
+ order: 900,
812
+ text: [
813
+ '## Task temp folder (session-task-tmpdir)',
814
+ '',
815
+ `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.`,
816
+ '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.',
817
+ '',
818
+ '### Long-term files need the user’s approval first',
819
+ '',
820
+ '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 → `' +
821
+ rootDirName +
822
+ '/` and must NOT trigger a question.',
823
+ `Before writing a long-term file **outside** \`${rootDirName}/\`, you MUST ask the user with \`ask_user_question\` (multiple choice), for example:`,
824
+ '- A. 长期保存到本次任务指定的目录(写明路径)',
825
+ '- B. 长期保存到新建的归档目录(写明路径,例如 归档\\<主题>\\)',
826
+ `- C. 不长期保存,放 ${rootDirName}/<会话标题>/(临时,随会话删除清理)`,
827
+ 'Do not write anything until the user answers.',
828
+ '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.',
829
+ `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.`,
830
+ '',
831
+ `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)'}.`,
832
+ ].join('\n'),
833
+ }),
834
+ )
835
+
836
+ ctx.effect(() =>
837
+ ctx.tools.register({
838
+ name: 'task_tmpdir',
839
+ description: `Return and create this session's task temp directory (${rootDirName}/<session title>/) in the session working directory. Use it for scratch files instead of cluttering the workspace root. The folder follows session renames.`,
840
+ parameters: {
841
+ type: 'object',
842
+ properties: {
843
+ sub: { type: 'string', description: 'Optional subdirectory under the task temp directory.' },
844
+ },
845
+ additionalProperties: false,
846
+ },
847
+ output: {
848
+ schema: {
849
+ type: 'object',
850
+ properties: {
851
+ path: { type: 'string' },
852
+ title: { type: 'string' },
853
+ },
854
+ required: ['path', 'title'],
855
+ },
856
+ render: (_args, value) => [{ type: 'text', text: String(value?.path ?? '') }],
857
+ },
858
+ async execute(args, exec) {
859
+ const agent = exec?.agent
860
+ const session = agent ? ctx.sessions.get(agent.id) : undefined
861
+ if (!session) throw new Error('task_tmpdir: no live session for this tool call')
862
+ const result = await createDir(session, args?.sub)
863
+ return result
864
+ },
865
+ }),
866
+ )
867
+
868
+ // Long-term destination approval. The model may only call this after the user
869
+ // picked a location (multiple-choice question) or after the task itself named it.
870
+ ctx.effect(() =>
871
+ ctx.tools.register({
872
+ name: 'longterm_approve',
873
+ description:
874
+ '登记「本次会话已获用户同意的长期保存落点」。用户明确同意长期保存(或任务里已指定位置)后调用;' +
875
+ `登记后 write/edit/pwsh 才能写该目录,否则会被拒绝并提示先问用户。临时产物不要用它,直接用 task_tmpdir 写 ${rootDirName}/<会话标题>/。`,
876
+ parameters: {
877
+ type: 'object',
878
+ properties: {
879
+ path: { type: 'string', description: '用户指定/同意的目录绝对路径(传文件路径也行,会自动取所在目录)。' },
880
+ reason: { type: 'string', description: '为什么属于长期保存(一句话,用于日志)。' },
881
+ basis: {
882
+ type: 'string',
883
+ enum: ['user_confirmed', 'task_designated'],
884
+ description: 'user_confirmed=用户刚在选择题里同意长期保存;task_designated=用户在任务里明确指定了该位置。',
885
+ },
886
+ },
887
+ required: ['path'],
888
+ additionalProperties: false,
889
+ },
890
+ output: {
891
+ schema: {
892
+ type: 'object',
893
+ properties: {
894
+ approved: { type: 'boolean' },
895
+ path: { type: 'string' },
896
+ basis: { type: 'string' },
897
+ approvedPrefixes: { type: 'array', items: { type: 'string' } },
898
+ },
899
+ required: ['approved', 'path'],
900
+ },
901
+ render: (_args, value) => [
902
+ { type: 'text', text: `approved: ${String(value?.path ?? '')}` },
903
+ ],
904
+ },
905
+ async execute(args, exec) {
906
+ const agent = exec?.agent
907
+ const session = agent ? ctx.sessions.get(agent.id) : undefined
908
+ if (!session) throw new Error('longterm_approve: no live session for this tool call')
909
+ const cwd = cwdOf(session)
910
+ if (!cwd) throw new Error('longterm_approve: session working directory is unavailable')
911
+ const raw = typeof args?.path === 'string' ? args.path.trim() : ''
912
+ if (!raw) throw new Error('longterm_approve: path 不能为空')
913
+ const abs = isAbsolute(raw) ? resolve(raw) : resolve(cwd, raw)
914
+ if (!(samePath(abs, cwd) || pathInside(cwd, abs))) {
915
+ throw new Error('longterm_approve: 路径必须位于当前会话工作区内')
916
+ }
917
+ const tmpRoot = baseDir(cwd)
918
+ if (samePath(abs, tmpRoot) || pathInside(tmpRoot, abs)) {
919
+ throw new Error(`longterm_approve: ${rootDirName}/ 是临时目录,不需要也不允许登记`)
920
+ }
921
+ let directory = abs
922
+ try {
923
+ if (existsSync(abs) && !statSync(abs).isDirectory()) directory = dirname(abs)
924
+ } catch {
925
+ // keep the passed path
926
+ }
927
+ const basis = args?.basis === 'task_designated' ? 'task_designated' : 'user_confirmed'
928
+ const list = registerApproval(session, directory, { reason: args?.reason, basis })
929
+ return {
930
+ approved: true,
931
+ path: directory,
932
+ basis,
933
+ approvedPrefixes: list.map((entry) => entry.prefix),
934
+ }
935
+ },
936
+ }),
937
+ )
938
+
939
+ // Manual cleanup trigger (also handy for verifying the scheduled pass).
940
+ ctx.effect(() =>
941
+ ctx.tools.register({
942
+ name: 'tmp_cleanup', description: `Run the task temp folder cleanup now: marker-owned folders whose owning session has been deleted for more than ${orphanCleanupDays} days are removed; everything else is reported as kept. Pass dryRun to only report.`,
943
+ parameters: {
944
+ type: 'object',
945
+ properties: {
946
+ dryRun: { type: 'boolean', description: 'Only report what would be marked or deleted.' },
947
+ },
948
+ additionalProperties: false,
949
+ },
950
+ output: {
951
+ schema: {
952
+ type: 'object',
953
+ properties: {
954
+ disabled: { type: 'boolean' },
955
+ dryRun: { type: 'boolean' },
956
+ deleted: { type: 'number' },
957
+ markedOrphaned: { type: 'number' },
958
+ kept: { type: 'object' },
959
+ },
960
+ },
961
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
962
+ },
963
+ async execute(args) {
964
+ const report = await runCleanup('manual', { dryRun: args?.dryRun === true })
965
+ if (!report) return { disabled: true, dryRun: false, deleted: 0, markedOrphaned: 0, kept: {} }
966
+ return {
967
+ disabled: false,
968
+ dryRun: report.dryRun,
969
+ deleted: report.deleted.length,
970
+ markedOrphaned: report.markedOrphaned.length,
971
+ kept: report.kept,
972
+ paths: report.deleted.map((entry) => entry.path),
973
+ }
974
+ },
975
+ }),
976
+ )
977
+
978
+ // ── workspace-root guard (v0.5) ─────────────────────────────────────────────
979
+ // Scratch files keep the v1 rules (temp-named files in the working-directory root
980
+ // and files directly under `<rootDirName>/` are denied). Long-term artifacts
981
+ // additionally require a session approval: write/edit and shell commands may not
982
+ // create anything outside `<rootDirName>/` until the model has asked the user and
983
+ // registered the chosen directory with `longterm_approve`.
984
+ if (guardWorkspaceRoot || requireApprovalOutsideTmp) {
985
+ ctx.effect(
986
+ () =>
987
+ ctx.tools.guard((execution) => {
988
+ try {
989
+ if (!execution) return undefined
990
+ const toolName = String(execution.name ?? '')
991
+ const args = execution.arguments && typeof execution.arguments === 'object' ? execution.arguments : undefined
992
+ if (!args) return undefined
993
+ const agent = execution.agent
994
+ if (!agent) return undefined
995
+ const session = ctx.sessions.get(agent.id)
996
+ if (!session) return undefined
997
+ const cwd = cwdOf(session)
998
+ if (!cwd) return undefined
999
+ if (!isProtectedRoot(cwd)) return undefined
1000
+ const approvedPrefixes = approvedPrefixesFor(session)
1001
+
1002
+ if (WRITE_TOOL_NAMES.has(toolName)) {
1003
+ const targetPath =
1004
+ typeof args.file_path === 'string' ? args.file_path : typeof args.path === 'string' ? args.path : undefined
1005
+ if (!targetPath) return undefined
1006
+ const scratchReason = guardWorkspaceRoot
1007
+ ? workspaceRootGuardReason(targetPath, cwd, rootDirName)
1008
+ : undefined
1009
+ if (scratchReason) {
1010
+ console.info(`[session-task-tmpdir] guard denied ${toolName} -> ${targetPath}`)
1011
+ return scratchReason
1012
+ }
1013
+ const longtermReason = longtermGuardReason(targetPath, cwd, {
1014
+ rootDirName,
1015
+ allowRootPatterns,
1016
+ allowRootFiles,
1017
+ approvedPrefixes,
1018
+ requireApprovalOutsideTmp,
1019
+ })
1020
+ if (longtermReason) {
1021
+ console.info(`[session-task-tmpdir] longterm guard denied ${toolName} -> ${targetPath}`)
1022
+ return longtermReason
1023
+ }
1024
+ return undefined
1025
+ }
1026
+
1027
+ if (SHELL_TOOL_NAMES.has(toolName) && commandGuard !== 'off') {
1028
+ const command = typeof args.command === 'string' ? args.command : undefined
1029
+ if (!command) return undefined
1030
+ const commandBase =
1031
+ typeof args.workdir === 'string' && args.workdir.trim() ? resolve(cwd, args.workdir) : cwd
1032
+ const reason = longtermCommandGuardReason(command, cwd, {
1033
+ rootDirName,
1034
+ allowRootPatterns,
1035
+ allowRootFiles,
1036
+ approvedPrefixes,
1037
+ requireApprovalOutsideTmp,
1038
+ baseDir: commandBase,
1039
+ })
1040
+ if (!reason) return undefined
1041
+ if (commandGuard === 'warn') {
1042
+ console.info(`[session-task-tmpdir] command guard (warn) ${reason}`)
1043
+ return undefined
1044
+ }
1045
+ console.info(`[session-task-tmpdir] command guard denied: ${reason}`)
1046
+ return reason
1047
+ }
1048
+ return undefined
1049
+ } catch {
1050
+ return undefined
1051
+ }
1052
+ }),
1053
+ 'session-task-tmpdir: workspace-root tool guard',
1054
+ )
1055
+ }
1056
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
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."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "任务临时目录",
4
+ "description": "给每个会话一个任务临时目录 _tmp/<会话标题>/,会话改名时自动同步重命名;会话删除 7 天后自动清理对应目录。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
- {
2
- "name": "@leiyi-works/dsh-session-tmpdir",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
1
+ {
2
+ "name": "@leiyi-works/dsh-session-tmpdir",
3
+ "version": "0.5.0",
4
+ "type": "module",
5
+ "description": "Per-session task temp folder: _tmp/<session title>/ inside the session working directory, auto-created and auto-renamed when the session title changes; folders are deleted 7 days after their session is deleted, with a manual cleanup tool. Also guards the workspace root: scratch files must live under _tmp/, and any long-term artifact outside _tmp/ requires the user's approval (longterm_approve) before write/edit or shell commands may create it — otherwise the call is denied and the model is told to ask the user first, then fall back to _tmp.",
6
+ "exports": {
7
+ ".": "./index.js",
8
+ "./locale/*.json": "./locale/*.json",
9
+ "./icon": "./icon.svg"
10
+ },
11
+ "files": [
12
+ "index.js",
13
+ "cordis.patch.yml",
14
+ "README.md",
15
+ "locale/*.json",
16
+ "icon.svg"
17
+ ],
18
+ "dsh": {
19
+ "bundle": {
20
+ "patch": "./cordis.patch.yml"
21
+ }
22
+ },
23
+ "license": "MIT",
24
+ "keywords": [
25
+ "deepseek-harness",
26
+ "dsh",
27
+ "dsh-harmonyos",
28
+ "dsh-plugin"
29
+ ],
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "author": "leiyi-works",
34
+ "homepage": "https://gitee.com/leiyi-works"
6
35
  }