@leiyi-works/dsh-session-tmpdir 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +190 -187
  2. package/index.js +2340 -2178
  3. package/package.json +1 -1
package/index.js CHANGED
@@ -1,2178 +1,2340 @@
1
- import { existsSync, statSync } from 'node:fs'
2
- import { appendFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
3
- import { homedir, tmpdir } from 'node:os'
4
- import { basename, dirname, isAbsolute, join, parse, 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
- * v0.7 closes the write channels that used to bypass the guard:
27
- * - every call is classified by capability (`toolWritePlan`): `write`/`edit`, shell
28
- * tools, code-execution tools (`python`, `node`, …), delivery tools (`publish`) and
29
- * unknown tools that declare path arguments; `present` is display-only;
30
- * - destinations outside the workspace are classified as well — DSH's own home,
31
- * caches and the OS temp directory are allowed, anything else is long-term
32
- * (`outsideAllow` extends that list);
33
- * - shell parsing is platform aware (drive paths on Windows, `/`-rooted paths on
34
- * HarmonyOS/POSIX Hosts) and covers POSIX create verbs;
35
- * - `longterm_approve` may register a directory outside the workspace (never a
36
- * filesystem root or the home directory itself).
37
- *
38
- * Cleanup (default: 7 days after the owning session is deleted):
39
- * - once a day every registered workspace's `<rootDirName>` is scanned;
40
- * - a folder whose session still exists (live or persisted) is always kept;
41
- * - a folder whose session is gone is stamped `orphanedAt` on first sight;
42
- * - once `orphanedAt` is older than `orphanCleanupDays`, the folder is deleted.
43
- * Folders without our marker are never touched.
44
- *
45
- * Attachment garbage collection (v0.6), same schedule and grace period:
46
- * - the Host attachment store (`<DSH_HOME>/attachments`) is content-addressed and never
47
- * garbage collected, so deleting a conversation used to leave its blobs on disk forever;
48
- * - every tick the ledger `<DSH_HOME>/data/session-tmpdir-attachments.json` records which
49
- * attachment ids each stored session references (read through `sessionPersistence`, so
50
- * no log format is assumed); only a changed revision is re-read;
51
- * - a session that disappears is stamped `orphanedAt`; after `attachmentCleanupDays` the
52
- * blobs it alone referenced are deleted (any blob still referenced is always kept);
53
- * - blobs nobody references and older than the grace period are swept as well, which
54
- * reclaims the historical leftovers of sessions deleted before this feature existed;
55
- * - every deletion is appended to `session-tmpdir-attachments-gc.jsonl`, and a blob
56
- * written within the last hour is never touched.
57
- */
58
-
59
- const MARKER_FILE = '.dsh-task.json'
60
- const DEFAULT_ROOT = '_tmp'
61
- const DEFAULT_MAX_NAME = 60
62
- const DEFAULT_ORPHAN_DAYS = 7
63
- const DEFAULT_CLEANUP_HOURS = 24
64
- const STARTUP_CLEANUP_DELAY_MS = 60_000
65
- const FALLBACK_PREFIX = 'session-'
66
- const DAY_MS = 86_400_000
67
-
68
- // ── attachment garbage collection (v0.6) ────────────────────────────────────
69
- /** Ledger file (under `<DSH_HOME>/data/`) recording which attachments each session used. */
70
- const ATTACHMENT_LEDGER_FILE = 'session-tmpdir-attachments.json'
71
- /** Append-only audit log of every attachment the collector deleted. */
72
- const ATTACHMENT_GC_LOG_FILE = 'session-tmpdir-attachments-gc.jsonl'
73
- const ATTACHMENT_LEDGER_VERSION = 1
74
- /** `attachmentId` values look like `sha256:<64 lowercase hex>`. */
75
- const ATTACHMENT_ID_PATTERN = /^sha256:([0-9a-f]{64})$/i
76
- /** Never delete a blob written this recently — it may belong to a message not yet persisted. */
77
- const ATTACHMENT_MIN_AGE_MS = 3_600_000
78
- /** Upper bound on read pages per session, so one corrupt log cannot hang the sweep. */
79
- const ATTACHMENT_READ_PAGE_LIMIT = 200
80
- /** Events per read page: keeps peak memory bounded on very long sessions. */
81
- const ATTACHMENT_READ_PAGE_SIZE = 500
82
- /** Tool names whose path arguments create or overwrite a file. */
83
- const WRITE_TOOL_NAMES = new Set(['write', 'edit', 'multi_edit', 'apply_patch', 'str_replace_editor'])
84
- /** Tool names that run a shell command (their write targets must be parsed from text). */
85
- const SHELL_TOOL_NAMES = new Set(['pwsh', 'bash', 'sh', 'zsh', 'shell', 'terminal', 'cmd', 'powershell'])
86
- /** Tool names that execute code in a Host-embedded runtime; their writes are scanned statically. */
87
- const CODE_TOOL_NAMES = new Set([
88
- 'python',
89
- 'python3',
90
- 'py',
91
- 'node',
92
- 'run_code',
93
- 'execute_code',
94
- 'code_interpreter',
95
- 'ipython',
96
- 'ruby',
97
- 'perl',
98
- ])
99
- /** Delivery tools: `publish` (HarmonyOS DSHM) copies a file into a delivery folder; `present` only shows it. */
100
- const PUBLISH_TOOL_NAMES = new Set(['publish', 'present'])
101
- /** Argument names that can carry a file or directory target. */
102
- const PATH_ARG_PATTERN =
103
- /^(?:file_?paths?|paths?|files?|target|targets|target_?path|destination|dest|dst|dest_?path|to|output|output_?path|output_?dir|out|out_?path|dir|directory|directory_?path|folder|save_?path|save|filename|file_?name|location|locations|download_?dir|upload_?dir)$/i
104
- /** Source-only path arguments (the read side of a copy/publish). */
105
- const SOURCE_PATH_ARG_PATTERN = /^(?:source|src|from|origin|input|input_?path|source_?path)$/i
106
- /** Tool name/description words that indicate a write-capable tool. */
107
- const WRITE_HINT_PATTERN =
108
- /\b(?:write|writes|writefile|save|create|export|publish|present|download|upload|copy|move|rename|delete|remove|mkdir|install|render|convert|recalculate|generate|produce|dump|store|merge|split|unzip|unpack|extract|replace|patch|append|edit|output)\b/i
109
- /** Read-only tool names: skipped even when their description mentions a write in a negation. */
110
- const READ_ONLY_TOOL_PATTERN = /^(?:read|list|get|show|view|check|status|query|search|find|glob|grep|count|stat)(?:[_\-.]|$)/i
111
- /** The plugin's own tools must always pass their own guard (approval must not self-lock). */
112
- const SELF_TOOL_NAMES = new Set(['task_tmpdir', 'longterm_approve', 'tmp_cleanup'])
113
- /** Windows device names that are never files on disk. */
114
- const WINDOWS_DEVICE_PATTERN = /^(?:nul|con|prn|aux|clock\$|com[0-9]|lpt[0-9])$/i
115
- /** `scheme://...` tokens are stripped before shell path scanning (a URL contains `s:/`). */
116
- const URL_PATTERN = /[A-Za-z][A-Za-z0-9+.\-]*:\/\/[^\s'"`]*/g
117
- /** File names that are scratch artifacts wherever they land. */
118
- const TEMP_FILE_PATTERNS = [/^_tmp/i, /^tmp_/i, /\.tmp$/i, /\.temp$/i, /\.part$/i, /^~\$/]
119
- const DEFAULT_ALLOW_ROOT_PATTERNS = ['dsh-*']
120
- const DEFAULT_ALLOW_ROOT_FILES = ['.dsh-standing-rules.md']
121
- const DEFAULT_COMMAND_GUARD = 'deny'
122
- const DEFAULT_PUBLISH_GUARD = 'deny'
123
- /** Command text that can create a directory/file; used before scanning for paths (v0.7: POSIX verbs). */
124
- const CREATE_VERB_PATTERN =
125
- /\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
126
- /** Redirection source shared by the global form. */
127
- const REDIRECT_SOURCE =
128
- '(?:^|[\\s;&|])(?:>>|\\d?>>?)\\s*(?:"([^"]+)"|\'([^\']+)\'|([^\\s;&|]+))'
129
- /** Every redirection target in a command (v0.7: all of them, not only the first). */
130
- const REDIRECT_ALL_PATTERN = new RegExp(REDIRECT_SOURCE, 'g')
131
- /** Windows absolute path tokens inside a command string (not part of a URL). */
132
- const WIN_ABS_PATH_PATTERN = /(?<![A-Za-z0-9])([A-Za-z]:[\\/][^\s'"`,;|&)}\]>]+)/g
133
- /** POSIX absolute path tokens inside a command string (HarmonyOS/POSIX Hosts). */
134
- const POSIX_ABS_PATH_PATTERN = /(?:^|[\s'"`(=])(\/(?!\/)[^\s'"`,;|&)}\]<>]+)/g
135
- /** Pseudo paths that are never created on disk. */
136
- const DEVICE_PATH_PATTERN = /^\/(?:dev\/(?:null|zero|stdin|stdout|stderr|tty|urandom|random|shm)|proc|sys)(?:\/|$)/
137
- /** `_tmp`-like directory segments that always mean "scratch". */
138
- const SCRATCH_SEGMENT_NAMES = new Set(['_tmp'])
139
- /** Write signals inside a code string (Python/JS/Ruby best-effort static scan). */
140
- const CODE_WRITE_SIGNAL =
141
- /(?:open\s*\([^()]*,\s*['"][^'"]*[wax+][^'"]*['"]|\.write_text\s*\(|\.write_bytes\s*\(|shutil\.(?:copy|copy2|copyfile|move|copytree|rmtree)|os\.(?:replace|rename|remove|unlink|mkdir|makedirs|rmdir|removedirs|mknod|symlink|link)|json\.dump\s*\(|pickle\.dump\s*\(|\.to_csv\s*\(|\.to_excel\s*\(|\.to_json\s*\(|\.to_pickle\s*\(|\.to_parquet\s*\(|\.savefig\s*\(|\.save\s*\(|imwrite\s*\(|np\.save\w*\s*\(|writeFile(?:Sync)?\s*\(|appendFile(?:Sync)?\s*\(|createWriteStream\s*\(|writeTextFile\s*\(|fs\.(?:copyFile\w*|rename\w*|unlink\w*|mkdir\w*|rm\w*|writeFile\w*|appendFile\w*)|\.mkdir\w*\s*\(|\.rmdir\w*\s*\(|mkdirSync\s*\()/g
142
- /** String literals that look like file paths inside code (absolute, or relative with a separator/known extension). */
143
- const CODE_PATH_LITERAL =
144
- /(['"])((?:\/[^'"\n]{1,400}|[A-Za-z]:[\\/][^'"\n]{1,400}|\.{1,2}[\\/][^'"\n]{1,400}|[A-Za-z0-9_.\-]+[\\/][^'"\n]{1,400}|[A-Za-z0-9_.\-]+\.(?:md|txt|json|jsonl|csv|tsv|xlsx|docx|pptx|pdf|png|jpe?g|gif|webp|mp4|mov|mp3|wav|html?|xml|ya?ml|zip|tar|gz|py|js|ts|mjs|sh)))\1/g
145
- /** Distance (chars) within which a write signal and a path literal are treated as one statement. */
146
- const CODE_SIGNAL_WINDOW = 300
147
- /** v0.7: Windows desktop vs HarmonyOS/POSIX device. */
148
- const IS_WINDOWS = process.platform === 'win32'
149
-
150
- export const name = 'session-task-tmpdir'
151
-
152
- export const inject = ['sessions', 'sessionTitle', 'workingDirectory', 'systemPrompt', 'tools']
153
-
154
- /** Strip characters that are illegal in Windows/POSIX directory names and bound the length. */
155
- export function sanitizeTitle(raw, maxLength = DEFAULT_MAX_NAME) {
156
- let text = String(raw ?? '')
157
- .normalize('NFC')
158
- // eslint-disable-next-line no-control-regex
159
- .replace(/[\\/:*?"<>|\u0000-\u001f]+/g, '-')
160
- .replace(/\s+/g, ' ')
161
- .trim()
162
- // Windows: names may not end with a dot or space
163
- text = text.replace(/^[.\s]+|[.\s]+$/g, '')
164
- if (!text) return ''
165
- if (text.length > maxLength) text = text.slice(0, maxLength).trim()
166
- text = text.replace(/^[.\s]+|[.\s]+$/g, '')
167
- return text === '.' || text === '..' ? '' : text
168
- }
169
-
170
- function readConfig(config) {
171
- const c = config && typeof config === 'object' ? config : {}
172
- const rootDirName = typeof c.rootDirName === 'string' && c.rootDirName.trim() ? c.rootDirName.trim() : DEFAULT_ROOT
173
- const includeSubagents = c.includeSubagents === true
174
- const maxNameLength = Number.isInteger(c.maxNameLength) && c.maxNameLength > 0 ? c.maxNameLength : DEFAULT_MAX_NAME
175
- const orphanCleanupDays = Number.isFinite(c.orphanCleanupDays) && c.orphanCleanupDays >= 0 ? c.orphanCleanupDays : DEFAULT_ORPHAN_DAYS
176
- const cleanupIntervalHours = Number.isFinite(c.cleanupIntervalHours) && c.cleanupIntervalHours >= 1 ? c.cleanupIntervalHours : DEFAULT_CLEANUP_HOURS
177
- const cleanupDryRun = c.cleanupDryRun === true
178
- const attachmentCleanup = c.attachmentCleanup !== false
179
- const attachmentCleanupDays =
180
- Number.isFinite(c.attachmentCleanupDays) && c.attachmentCleanupDays >= 0 ? c.attachmentCleanupDays : orphanCleanupDays
181
- const attachmentSweepOrphans = c.attachmentSweepOrphans !== false
182
- const attachmentsDir =
183
- typeof c.attachmentsDir === 'string' && c.attachmentsDir.trim() ? c.attachmentsDir.trim() : join(resolveDshHome(), 'attachments')
184
- const guardWorkspaceRoot = c.guardWorkspaceRoot !== false
185
- const requireApprovalOutsideTmp = c.requireApprovalOutsideTmp !== false
186
- const allowRootPatterns = toStringList(c.allowRootPatterns, DEFAULT_ALLOW_ROOT_PATTERNS)
187
- const allowRootFiles = toStringList(c.allowRootFiles, DEFAULT_ALLOW_ROOT_FILES)
188
- const commandGuard = ['deny', 'warn', 'off'].includes(c.commandGuard) ? c.commandGuard : DEFAULT_COMMAND_GUARD
189
- // ── v0.7: write-channel coverage ─────────────────────────────────────────
190
- /** Guard writes that land outside the workspace (deny | warn | off). */
191
- const guardOutsideWorkspace = ['deny', 'warn', 'off'].includes(c.guardOutsideWorkspace)
192
- ? c.guardOutsideWorkspace
193
- : 'deny'
194
- /** Guard delivery tools (`publish`/`present` with a copy target): deny | warn | off. */
195
- const publishGuard = ['deny', 'warn', 'off'].includes(c.publishGuard) ? c.publishGuard : DEFAULT_PUBLISH_GUARD
196
- /** Statically scan code-execution tools (python/node) for file writes. */
197
- const guardCodeTools = c.guardCodeTools !== false
198
- /** Also inspect tools the plugin does not know by name, using their schema/description. */
199
- const guardUnknownTools = c.guardUnknownTools !== false
200
- /** Extra tool names per channel, appended to the built-in sets. */
201
- const extraWriteTools = toStringList(c.writeToolNames, [])
202
- const extraPublishTools = toStringList(c.publishToolNames, [])
203
- const extraCodeTools = toStringList(c.codeToolNames, [])
204
- /** Extra absolute directories that may be written outside the workspace (globs). */
205
- const outsideAllow = toStringList(c.outsideAllow, [])
206
- /** Base directory used to resolve a relative `publish` target (e.g. HarmonyOS `Download/`). */
207
- const publishBaseDir = typeof c.publishBaseDir === 'string' && c.publishBaseDir.trim() ? c.publishBaseDir.trim() : undefined
208
- return {
209
- rootDirName,
210
- includeSubagents,
211
- maxNameLength,
212
- orphanCleanupDays,
213
- cleanupIntervalHours,
214
- cleanupDryRun,
215
- guardWorkspaceRoot,
216
- requireApprovalOutsideTmp,
217
- allowRootPatterns,
218
- allowRootFiles,
219
- commandGuard,
220
- guardOutsideWorkspace,
221
- publishGuard,
222
- guardCodeTools,
223
- guardUnknownTools,
224
- writeToolNames: [...new Set([...WRITE_TOOL_NAMES, ...extraWriteTools])],
225
- publishToolNames: [...new Set([...PUBLISH_TOOL_NAMES, ...extraPublishTools])],
226
- codeToolNames: [...new Set([...CODE_TOOL_NAMES, ...extraCodeTools])],
227
- shellToolNames: [...SHELL_TOOL_NAMES],
228
- outsideAllow,
229
- publishBaseDir,
230
- attachmentCleanup,
231
- attachmentCleanupDays,
232
- attachmentSweepOrphans,
233
- attachmentsDir,
234
- }
235
- }
236
-
237
- /** Accept a string or an array of strings as a config list, falling back to `fallback`. */
238
- function toStringList(value, fallback) {
239
- if (typeof value === 'string' && value.trim()) return [value.trim()]
240
- if (Array.isArray(value)) {
241
- const list = value.filter((item) => typeof item === 'string' && item.trim()).map((item) => item.trim())
242
- if (list.length > 0) return list
243
- }
244
- return [...fallback]
245
- }
246
-
247
- /** Path comparison: case-insensitive on Windows, exact and separator-normalized elsewhere. */
248
- function samePath(a, b) {
249
- if (typeof a !== 'string' || typeof b !== 'string') return false
250
- const normalize = (value) => {
251
- const text = resolve(value).replace(/[\\/]+$/, '')
252
- return IS_WINDOWS ? text.replace(/\\/g, '/').toLowerCase() : text
253
- }
254
- return normalize(a) === normalize(b)
255
- }
256
-
257
- /**
258
- * Reject scratch-file writes that land in the wrong place:
259
- * temp-looking names directly in the working-directory root, or any file directly
260
- * under `<cwd>/<rootDirName>/` instead of a session subfolder.
261
- *
262
- * @param {string} targetPath the write/edit `file_path` argument (absolute or relative to cwd)
263
- * @param {string} cwd the session working directory
264
- * @param {string} [rootDirName] temp root name (default `_tmp`)
265
- * @returns {string | undefined} denial reason for the tool guard, or undefined to allow
266
- */
267
- export function workspaceRootGuardReason(targetPath, cwd, rootDirName = DEFAULT_ROOT) {
268
- if (typeof targetPath !== 'string' || targetPath.trim() === '') return undefined
269
- if (typeof cwd !== 'string' || cwd.trim() === '') return undefined
270
- let abs
271
- try {
272
- abs = isAbsolute(targetPath) ? targetPath : resolve(cwd, targetPath)
273
- } catch {
274
- return undefined
275
- }
276
- const name = basename(abs)
277
- if (!name) return undefined
278
- if (samePath(dirname(abs), cwd) && TEMP_FILE_PATTERNS.some((pattern) => pattern.test(name))) {
279
- return (
280
- `工作区根目录不能放临时文件(${name})。请先调用 task_tmpdir 获取 ` +
281
- `${rootDirName}/<会话标题>/ 的准确路径,把临时文件写进那个目录。`
282
- )
283
- }
284
- if (samePath(dirname(abs), join(cwd, rootDirName))) {
285
- return (
286
- `${rootDirName}/ 根目录不能直接放文件(${name})。请先调用 task_tmpdir,` +
287
- `把文件写入 ${rootDirName}/<会话标题>/ 子目录。`
288
- )
289
- }
290
- return undefined
291
- }
292
-
293
- // ── long-term destination guard (v0.5) ─────────────────────────────────────────
294
-
295
- /**
296
- * Normalized path used for comparisons: forward slashes on Windows (case folded),
297
- * untouched on POSIX where `\` is a legal filename character (v0.7, review M10).
298
- */
299
- function normalizeForCompare(target) {
300
- const text = resolve(target).replace(/[\\/]+$/, '')
301
- return IS_WINDOWS ? text.replace(/\\/g, '/').toLowerCase() : text
302
- }
303
-
304
- /**
305
- * True when `child` is `parent` or lives inside it (case-insensitive, separator
306
- * normalized). v0.7: uses `/` on every platform, so the check also works on
307
- * HarmonyOS/POSIX Hosts where `resolve()` never emits a backslash.
308
- */
309
- export function pathInside(parent, child) {
310
- if (typeof parent !== 'string' || typeof child !== 'string') return false
311
- if (!parent.trim() || !child.trim()) return false
312
- const p = normalizeForCompare(parent)
313
- const c = normalizeForCompare(child)
314
- return c === p || c.startsWith(`${p}/`)
315
- }
316
-
317
- /** First path segment of `abs` relative to `cwd`, or undefined when not inside `cwd`. */
318
- export function firstSegmentUnder(cwd, abs) {
319
- if (typeof cwd !== 'string' || typeof abs !== 'string') return undefined
320
- const base = resolve(cwd)
321
- const target = resolve(abs)
322
- if (!(normalizeForCompare(base) === normalizeForCompare(target) || pathInside(base, target))) return undefined
323
- if (normalizeForCompare(base) === normalizeForCompare(target)) return ''
324
- const rest = target.slice(base.replace(/[\\/]+$/, '').length).replace(/^[\\/]+/, '')
325
- const [first] = rest.split(/[\\/]+/).filter(Boolean)
326
- return first ?? ''
327
- }
328
-
329
- /** Simple case-insensitive glob matcher (`*` and `?` only). */
330
- export function globMatch(name, patterns) {
331
- const text = String(name ?? '')
332
- for (const raw of patterns ?? []) {
333
- const pattern = String(raw ?? '').trim()
334
- if (!pattern) continue
335
- const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
336
- try {
337
- if (new RegExp(`^${escaped}$`, 'i').test(text)) return true
338
- } catch {
339
- // an unusable pattern never matches
340
- }
341
- }
342
- return false
343
- }
344
-
345
- /**
346
- * Decide whether a `write`/`edit` target outside the temp root may be written.
347
- *
348
- * Rules (v0.5):
349
- * - under `<cwd>/<rootDirName>/` → allowed (scratch);
350
- * - under an approved long-term prefix → allowed (session registered it via longterm_approve);
351
- * - root-level file → allowed only when explicitly allow-listed;
352
- * - first segment matching allowRootPatterns → allowed (plugin source trees by default);
353
- * - anything else → denied with the "ask the user first" protocol.
354
- *
355
- * @returns {string | undefined} denial reason, or undefined to allow
356
- */
357
- export function longtermGuardReason(targetPath, cwd, options = {}) {
358
- const {
359
- rootDirName = DEFAULT_ROOT,
360
- allowRootPatterns = DEFAULT_ALLOW_ROOT_PATTERNS,
361
- allowRootFiles = DEFAULT_ALLOW_ROOT_FILES,
362
- approvedPrefixes = [],
363
- requireApprovalOutsideTmp = true,
364
- } = options
365
- if (!requireApprovalOutsideTmp) return undefined
366
- if (typeof targetPath !== 'string' || targetPath.trim() === '') return undefined
367
- if (typeof cwd !== 'string' || cwd.trim() === '') return undefined
368
- let abs
369
- try {
370
- abs = isAbsolute(targetPath) ? targetPath : resolve(cwd, targetPath)
371
- } catch {
372
- return undefined
373
- }
374
- const base = resolve(cwd)
375
- if (!pathInside(base, abs)) return undefined
376
- const tmpRoot = join(base, rootDirName)
377
- if (pathInside(tmpRoot, abs)) return undefined
378
- if (approvedPrefixes.some((prefix) => pathInside(prefix, abs))) return undefined
379
- if (samePath(dirname(abs), base)) {
380
- const name = basename(abs)
381
- if (allowRootFiles.some((entry) => entry.toLowerCase() === name.toLowerCase())) return undefined
382
- if (globMatch(name, allowRootPatterns)) return undefined
383
- return (
384
- `工作区根目录不能新建/修改条目(${name})。若这份内容需要长期保存:先用 ask_user_question 征求用户意见,` +
385
- `用户同意后用 longterm_approve 登记用户指定的目录再写;用户不同意或属于临时产物 → 用 task_tmpdir 写到 ` +
386
- `${rootDirName}/<会话标题>/。`
387
- )
388
- }
389
- const first = firstSegmentUnder(base, abs)
390
- if (!first) return undefined
391
- if (globMatch(first, allowRootPatterns)) return undefined
392
- return (
393
- `「${first}」不在本次会话已批准的长期落点里。若这份内容需要长期保存:先用 ask_user_question 征求用户意见,` +
394
- `用户同意后调用 longterm_approve 登记用户指定的目录再写;用户不同意或属于临时产物 → 用 task_tmpdir 写到 ` +
395
- `${rootDirName}/<会话标题>/。`
396
- )
397
- }
398
-
399
- /**
400
- * Best-effort guard for shell tools: when a command may create something, scan its
401
- * literal absolute Windows paths. Any not-yet-existing path inside the workspace that is
402
- * neither scratch nor approved is denied. Paths that already exist are left alone (they are
403
- * usually sources for Copy-Item or files being edited) — this keeps false positives low.
404
- *
405
- * @returns {string | undefined} denial reason, or undefined to allow
406
- */
407
- export function longtermCommandGuardReason(command, workspaceRoot, options = {}) {
408
- const {
409
- rootDirName = DEFAULT_ROOT,
410
- allowRootPatterns = DEFAULT_ALLOW_ROOT_PATTERNS,
411
- allowRootFiles = DEFAULT_ALLOW_ROOT_FILES,
412
- approvedPrefixes = [],
413
- outsideAllow = [],
414
- requireApprovalOutsideTmp = true,
415
- guardOutsideWorkspace = 'deny',
416
- skipInside = false,
417
- baseDir,
418
- pathExists = (target) => existsSync(target),
419
- platform = process.platform,
420
- } = options
421
- if (!requireApprovalOutsideTmp) return undefined
422
- if (typeof command !== 'string' || command.trim() === '') return undefined
423
- if (typeof workspaceRoot !== 'string' || workspaceRoot.trim() === '') return undefined
424
- // v0.7 (review M2): every redirect target counts, not only the first, and `>>` is
425
- // parsed as one token instead of leaving a second `>` behind. Quoted text such as
426
- // `Write-Host "1 > 0"` and device names (`NUL`, `$null`) are not real targets.
427
- const redirectTokens = new Set()
428
- for (const match of command.matchAll(REDIRECT_ALL_PATTERN)) {
429
- const token = match[1] ?? match[2] ?? match[3]
430
- if (!token) continue
431
- const cleaned = token.replace(/["'`]+$/, '')
432
- if (!cleaned || /^>+$/.test(cleaned)) continue
433
- if (!looksLikePathValue(cleaned) && !FILE_EXTENSION_PATTERN.test(cleaned)) continue
434
- redirectTokens.add(token)
435
- }
436
- const hasRedirect = redirectTokens.size > 0
437
- if (!hasRedirect && !CREATE_VERB_PATTERN.test(command)) return undefined
438
- const base = resolve(workspaceRoot)
439
- const resolveBase = typeof baseDir === 'string' && baseDir.trim() ? resolve(baseDir) : base
440
- // v0.7 (review M3): strip `scheme://…` first — `https://` contains `s:/`, which the
441
- // Windows drive-path pattern would otherwise treat as a directory.
442
- const scanText = command.replace(URL_PATTERN, ' ')
443
- const pathPattern = platform === 'win32' ? WIN_ABS_PATH_PATTERN : POSIX_ABS_PATH_PATTERN
444
- const tokens = new Set([...redirectTokens])
445
- for (const match of scanText.matchAll(pathPattern)) tokens.add(match[1])
446
- const classifyOptions = {
447
- rootDirName,
448
- allowRootPatterns,
449
- allowRootFiles,
450
- approvedPrefixes,
451
- outsideAllow,
452
- requireApprovalOutsideTmp,
453
- guardOutsideWorkspace,
454
- }
455
- for (const raw of tokens) {
456
- if (!raw) continue
457
- const cleaned = String(raw).replace(/["'`]+$/, '')
458
- let abs
459
- try {
460
- const expanded = expandTildePath(cleaned)
461
- abs = isAbsolute(expanded) ? resolve(expanded) : resolve(resolveBase, expanded)
462
- } catch {
463
- continue
464
- }
465
- if (isDevicePath(abs)) continue
466
- const isRedirectTarget = redirectTokens.has(raw)
467
- const verdict = classifyWriteTarget(abs, base, classifyOptions)
468
- if (verdict.kind === 'allowed' || verdict.kind === 'skip') continue
469
- // Existing targets are usually sources of a copy or files being edited; keep the
470
- // historical low-false-positive behavior — except for redirect targets, which are
471
- // always written (v0.7 review M6).
472
- if (!isRedirectTarget && pathExists(abs)) continue
473
- if (verdict.kind === 'outside') {
474
- if (guardOutsideWorkspace === 'warn') {
475
- console.info(`[session-task-tmpdir] command guard (warn): ${abs}`)
476
- continue
477
- }
478
- return outsideWriteDenialReason(abs, { rootDirName, action: '执行这条命令' })
479
- }
480
- // inside the workspace but not approved / not scratch
481
- if (skipInside) continue
482
- const first = firstSegmentUnder(base, abs)
483
- if (samePath(dirname(abs), base)) {
484
- return (
485
- `命令会新建工作区根目录条目「${basename(abs)}」(${abs})。若需要长期保存:先用 ask_user_question 征求用户意见,` +
486
- `同意后 longterm_approve 登记目录再执行;临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
487
- )
488
- }
489
- return (
490
- `命令会新建工作区里的「${first || basename(abs)}」(${abs}),它不在本次会话已批准的长期落点里。` +
491
- `若需要长期保存:先用 ask_user_question 征求用户意见,同意后 longterm_approve 登记目录再执行;` +
492
- `临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
493
- )
494
- }
495
- return undefined
496
- }
497
-
498
- // ── v0.7: write-channel resolution (capability based, not a fixed tool list) ──
499
-
500
- /** Expand a leading `~` to the current user's home directory. */
501
- function expandTildePath(value) {
502
- if (typeof value !== 'string' || !value.trim()) return value
503
- const text = value.trim()
504
- if (text === '~') return homedir()
505
- if (text.startsWith('~/') || text.startsWith('~\\')) return join(homedir(), text.slice(2))
506
- return text
507
- }
508
-
509
- /** Forward-slash, lower-cased (on Windows) form used by path globs. */
510
- function slashedPath(value) {
511
- const text = String(value).replace(/\\/g, '/').replace(/\/+$/, '')
512
- return IS_WINDOWS ? text.toLowerCase() : text
513
- }
514
-
515
- /** True for `/dev/null`-style pseudo paths and Windows device names (never on disk). */
516
- function isDevicePath(abs) {
517
- if (typeof abs !== 'string') return false
518
- if (DEVICE_PATH_PATTERN.test(String(abs).replace(/\\/g, '/'))) return true
519
- if (!IS_WINDOWS) return false
520
- const name = basename(abs).trim()
521
- if (/^\$null$/i.test(name)) return true
522
- return WINDOWS_DEVICE_PATTERN.test(name.replace(/\$\d*$/, ''))
523
- }
524
-
525
- /** True when a path lives under the OS temp directory (`os.tmpdir()`, `/tmp`, `/var/tmp`). */
526
- export function isSystemTempPath(abs) {
527
- if (typeof abs !== 'string' || !abs.trim()) return false
528
- const tempDirs = [tmpdir(), '/tmp', '/var/tmp', '/dev/shm']
529
- return tempDirs.some((dir) => dir && pathInside(dir, abs))
530
- }
531
-
532
- /** True when any path segment is a scratch root (`_tmp`, configured root name). */
533
- export function isScratchPath(targetPath, rootDirName = DEFAULT_ROOT) {
534
- if (typeof targetPath !== 'string' || !targetPath.trim()) return false
535
- const segments = String(targetPath)
536
- .replace(/\\/g, '/')
537
- .split('/')
538
- .filter(Boolean)
539
- const names = new Set([...SCRATCH_SEGMENT_NAMES].map((name) => name.toLowerCase()))
540
- if (typeof rootDirName === 'string' && rootDirName.trim()) names.add(rootDirName.trim().toLowerCase())
541
- return segments.some((segment) => names.has(segment.toLowerCase()))
542
- }
543
-
544
- /**
545
- * Glob match for absolute path patterns: `*` stays inside one segment, `**` crosses
546
- * segments. Patterns may start with `~`; a pattern ending in `/**` also matches the
547
- * directory itself. Used for the `outsideAllow` list.
548
- */
549
- export function pathGlobMatch(targetPath, patterns = []) {
550
- if (typeof targetPath !== 'string' || !targetPath.trim()) return false
551
- let target
552
- try {
553
- target = slashedPath(resolve(expandTildePath(targetPath)))
554
- } catch {
555
- return false
556
- }
557
- for (const raw of patterns ?? []) {
558
- const text = String(raw ?? '').trim()
559
- if (!text) continue
560
- let pattern
561
- try {
562
- pattern = slashedPath(resolve(expandTildePath(text)))
563
- } catch {
564
- continue
565
- }
566
- if (target === pattern) return true
567
- if (pattern.endsWith('/**') && target === pattern.slice(0, -3)) return true
568
- const regex = pattern
569
- .replace(/[.+^${}()|[\]\\]/g, '\\$&')
570
- .replace(/\*\*/g, '\u0000')
571
- .replace(/\*/g, '[^/]*')
572
- .replace(/\?/g, '[^/]')
573
- .replace(/\u0000\//g, '(?:.*/)?')
574
- .replace(/\u0000/g, '.*')
575
- try {
576
- if (new RegExp(`^${regex}$`).test(target)) return true
577
- } catch {
578
- // an unusable pattern never matches
579
- }
580
- }
581
- return false
582
- }
583
-
584
- /** Directory + `/**` so `pathGlobMatch` covers everything inside it. */
585
- function dirGlob(directory) {
586
- const clean = String(directory ?? '').replace(/[\\/]+$/, '')
587
- return clean ? `${clean}/**` : clean
588
- }
589
-
590
- /**
591
- * Directories outside the workspace that tools may write without asking: DSH's own
592
- * home (configuration, credentials, plugin data), caches and the OS temp directory.
593
- * Everything else outside the workspace is a long-term destination (v0.7).
594
- */
595
- export function defaultOutsideAllow(dshHome) {
596
- const home = homedir()
597
- const directories = [
598
- join(home, '.dsh'),
599
- join(home, '.cache'),
600
- join(home, '.npm'),
601
- join(home, '.config'),
602
- join(home, '.local', 'share'),
603
- join(home, '.flova'),
604
- tmpdir(),
605
- ]
606
- if (typeof dshHome === 'string' && dshHome.trim()) directories.push(dshHome)
607
- if (!IS_WINDOWS) directories.push('/tmp', '/var/tmp', '/dev/shm', '/run/user', '/data/local/tmp', '/storage/emulated/0/Android/data')
608
- return directories.filter(Boolean).map(dirGlob)
609
- }
610
-
611
- /**
612
- * Classify one write target for the long-term guard.
613
- *
614
- * @returns {{kind:'allowed'|'inside-longterm'|'outside'|'skip', abs?:string, reason?:string, scratch?:boolean}}
615
- * `inside-longterm` = inside the workspace but not under `_tmp`/an approved prefix;
616
- * `outside` = outside the workspace and not in `outsideAllow`.
617
- */
618
- export function classifyWriteTarget(targetPath, cwd, options = {}) {
619
- const {
620
- rootDirName = DEFAULT_ROOT,
621
- allowRootPatterns = DEFAULT_ALLOW_ROOT_PATTERNS,
622
- allowRootFiles = DEFAULT_ALLOW_ROOT_FILES,
623
- approvedPrefixes = [],
624
- outsideAllow = [],
625
- requireApprovalOutsideTmp = true,
626
- guardOutsideWorkspace = 'deny',
627
- baseDir: baseDirOption,
628
- } = options
629
- if (!requireApprovalOutsideTmp) return { kind: 'allowed' }
630
- if (typeof targetPath !== 'string' || !targetPath.trim()) return { kind: 'skip' }
631
- const base = typeof cwd === 'string' && cwd.trim() ? resolve(cwd) : undefined
632
- const resolveBase = typeof baseDirOption === 'string' && baseDirOption.trim() ? resolve(baseDirOption) : base
633
- if (!base && !resolveBase) return { kind: 'skip' }
634
- let abs
635
- try {
636
- const expanded = expandTildePath(targetPath)
637
- abs = isAbsolute(expanded) ? resolve(expanded) : resolve(resolveBase ?? base, expanded)
638
- } catch {
639
- return { kind: 'skip' }
640
- }
641
- if (isDevicePath(abs)) return { kind: 'allowed', abs }
642
- // v0.7 (review M8): a `_tmp` segment only counts as scratch inside the workspace or
643
- // under the OS temp directory — `Desktop/_tmp/x.md` is still a long-term write.
644
- if (isScratchPath(abs, rootDirName) && ((base && pathInside(base, abs)) || isSystemTempPath(abs))) {
645
- return { kind: 'allowed', abs, scratch: true }
646
- }
647
- if (base && pathInside(base, abs)) {
648
- const reason = longtermGuardReason(abs, base, {
649
- rootDirName,
650
- allowRootPatterns,
651
- allowRootFiles,
652
- approvedPrefixes,
653
- requireApprovalOutsideTmp,
654
- })
655
- return reason ? { kind: 'inside-longterm', abs, reason } : { kind: 'allowed', abs }
656
- }
657
- if (approvedPrefixes.some((prefix) => pathInside(prefix, abs))) return { kind: 'allowed', abs }
658
- if (pathGlobMatch(abs, outsideAllow)) return { kind: 'allowed', abs }
659
- if (guardOutsideWorkspace === 'off') return { kind: 'allowed', abs }
660
- return { kind: 'outside', abs }
661
- }
662
-
663
- /** Denial reason for a long-term destination outside the workspace. */
664
- export function outsideWriteDenialReason(abs, options = {}) {
665
- const { rootDirName = DEFAULT_ROOT, action = '写入' } = options
666
- return (
667
- `「${basename(abs)}」在工作区之外(${abs}),属于长期保存位置:${action}前必须先征求用户意见——` +
668
- `用 ask_user_question 问用户;用户同意后用 longterm_approve 登记该目录再${action};` +
669
- `用户不同意或属于临时产物 → 用 task_tmpdir 写到 ${rootDirName}/<会话标题>/。`
670
- )
671
- }
672
-
673
- /** Argument names that name a write destination strongly (bare file names are allowed). */
674
- const STRONG_TARGET_KEYS = new Set([
675
- 'target',
676
- 'targets',
677
- 'target_path',
678
- 'destination',
679
- 'dest',
680
- 'dst',
681
- 'dest_path',
682
- 'to',
683
- 'output',
684
- 'output_path',
685
- 'output_dir',
686
- 'out',
687
- 'out_path',
688
- 'save_path',
689
- 'filename',
690
- ])
691
- /** "Looks like a file name" hint used only for strongly-named destination arguments. */
692
- const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9]{1,8}$/
693
-
694
- /**
695
- * True when a string value looks like a filesystem path. Enum-like values
696
- * (`this_session`, `@e3`, `#submit`, npm package ids, URLs) are rejected on purpose
697
- * so business arguments are not mistaken for write targets (v0.7 review M1/S2/S3).
698
- */
699
- export function looksLikePathValue(value) {
700
- if (typeof value !== 'string') return false
701
- const text = value.trim()
702
- if (!text || text.length > 512) return false
703
- if (/[\r\n]/.test(text)) return false
704
- URL_PATTERN.lastIndex = 0
705
- if (URL_PATTERN.test(text)) return false
706
- if (/^[@#$]/.test(text)) return false
707
- if (/^@[\w.-]+\//.test(text)) return false
708
- if (/^[A-Za-z]:/.test(text)) return true
709
- if (/^~[/\\]/.test(text)) return true
710
- if (/^\.{1,2}[/\\]/.test(text)) return true
711
- if (/[\\/]/.test(text)) return true
712
- return false
713
- }
714
-
715
- /**
716
- * Top-level path targets of a tool call.
717
- *
718
- * v0.7 (review M1): only top-level arguments are inspected — nested business objects
719
- * (`expect[].target`, `args.files`, …) are not filesystem targets — and arguments
720
- * declared as `enum` in the tool schema are skipped.
721
- */
722
- export function collectPathTargets(args, options = {}) {
723
- if (!args || typeof args !== 'object') return []
724
- const { schema } = options
725
- const enumKeys = new Set()
726
- const properties = schema?.parameters?.properties
727
- if (properties && typeof properties === 'object') {
728
- for (const [key, definition] of Object.entries(properties)) {
729
- if (definition && typeof definition === 'object' && Array.isArray(definition.enum)) {
730
- enumKeys.add(key.toLowerCase())
731
- }
732
- }
733
- }
734
- const out = []
735
- const push = (key, value) => {
736
- if (typeof value !== 'string' || !value.trim()) return
737
- const text = value.trim()
738
- if (looksLikePathValue(text)) out.push(text)
739
- else if (STRONG_TARGET_KEYS.has(key.toLowerCase()) && FILE_EXTENSION_PATTERN.test(text)) out.push(text)
740
- }
741
- for (const [key, value] of Object.entries(args)) {
742
- if (!PATH_ARG_PATTERN.test(key)) continue
743
- if (enumKeys.has(key.toLowerCase())) continue
744
- if (typeof value === 'string') push(key, value)
745
- else if (Array.isArray(value)) {
746
- for (const item of value) {
747
- if (typeof item === 'string') push(key, item)
748
- else if (item && typeof item === 'object' && typeof item.path === 'string') push(key, item.path)
749
- }
750
- }
751
- }
752
- return out
753
- }
754
-
755
- /**
756
- * Best-effort static guard for code-execution tools (`python`, `node`, …).
757
- *
758
- * The tool runs arbitrary code, so this cannot be complete: it pairs write signals
759
- * (`open(...,'w')`, `shutil.copy`, `Path.write_text`, `fs.writeFileSync`, …) with
760
- * path literals appearing in the same statement and classifies those literals.
761
- * Dynamically built paths are intentionally out of scope (documented boundary).
762
- */
763
- export function codeToolGuardReason(code, cwd, options = {}) {
764
- if (typeof code !== 'string' || !code.trim()) return undefined
765
- const rootDirName = options.rootDirName ?? DEFAULT_ROOT
766
- const signals = []
767
- CODE_WRITE_SIGNAL.lastIndex = 0
768
- let match
769
- while ((match = CODE_WRITE_SIGNAL.exec(code)) !== null) signals.push(match.index)
770
- if (signals.length === 0) return undefined
771
- const literals = []
772
- CODE_PATH_LITERAL.lastIndex = 0
773
- while ((match = CODE_PATH_LITERAL.exec(code)) !== null) {
774
- if (match[2]) literals.push({ index: match.index, literal: match[2] })
775
- }
776
- if (literals.length === 0) return undefined
777
- // O(S×L) → linear: signals are already ascending, so a single cursor finds the
778
- // nearest signal at or before `literal index + window` (v0.7 review A11).
779
- let cursor = 0
780
- let nearest = Number.NEGATIVE_INFINITY
781
- for (const entry of literals) {
782
- while (cursor < signals.length && signals[cursor] <= entry.index + CODE_SIGNAL_WINDOW) {
783
- nearest = signals[cursor]
784
- cursor += 1
785
- }
786
- if (!Number.isFinite(nearest) || entry.index - nearest > CODE_SIGNAL_WINDOW) continue
787
- const verdict = classifyWriteTarget(entry.literal, cwd, options)
788
- if (verdict.kind === 'outside') {
789
- if (options.guardOutsideWorkspace === 'warn') {
790
- console.info(`[session-task-tmpdir] code guard (warn): ${verdict.abs}`)
791
- continue
792
- }
793
- return `代码执行工具被拦截:${outsideWriteDenialReason(verdict.abs, { rootDirName, action: '写入' })}`
794
- }
795
- if (verdict.kind === 'inside-longterm' && !options.skipInside) {
796
- return `代码执行工具被拦截:${verdict.reason}(代码里的写入目标:${verdict.abs})`
797
- }
798
- }
799
- return undefined
800
- }
801
-
802
- /** Argument names of a delivery tool that name the copy destination. */
803
- const COPY_TARGET_KEYS = new Set([
804
- 'target',
805
- 'targets',
806
- 'target_path',
807
- 'destination',
808
- 'dest',
809
- 'dst',
810
- 'dest_path',
811
- 'to',
812
- 'output',
813
- 'output_path',
814
- 'output_dir',
815
- 'out',
816
- 'out_path',
817
- 'save_path',
818
- 'dir',
819
- 'directory',
820
- 'filename',
821
- ])
822
-
823
- /** First path argument of a write/edit-style tool call. */
824
- export function firstWriteTarget(args) {
825
- if (!args || typeof args !== 'object') return undefined
826
- const candidates = [args.file_path, args.file_paths, args.path, args.file, args.files]
827
- for (const candidate of candidates) {
828
- if (typeof candidate === 'string' && candidate.trim()) return candidate.trim()
829
- if (Array.isArray(candidate)) {
830
- for (const item of candidate) {
831
- if (typeof item === 'string' && item.trim()) return item.trim()
832
- if (item && typeof item === 'object' && typeof item.path === 'string' && item.path.trim()) {
833
- return item.path.trim()
834
- }
835
- }
836
- }
837
- }
838
- return undefined
839
- }
840
-
841
- /**
842
- * Copy destinations of a delivery tool (`publish`). Source/read arguments are
843
- * skipped on purpose: copying *from* a long-term folder is harmless.
844
- */
845
- export function publishWriteTargets(args) {
846
- if (!args || typeof args !== 'object') return []
847
- const out = []
848
- const push = (value) => {
849
- if (typeof value === 'string' && value.trim()) out.push(value.trim())
850
- }
851
- for (const [key, value] of Object.entries(args)) {
852
- const lower = key.toLowerCase()
853
- if (SOURCE_PATH_ARG_PATTERN.test(lower)) continue
854
- if (!COPY_TARGET_KEYS.has(lower)) continue
855
- if (typeof value === 'string') push(value)
856
- else if (Array.isArray(value)) value.forEach(push)
857
- else if (value && typeof value === 'object') {
858
- for (const nested of Object.values(value)) push(nested)
859
- }
860
- }
861
- const files = Array.isArray(args.files) ? args.files : []
862
- for (const file of files) {
863
- if (typeof file === 'string') push(file)
864
- else if (file && typeof file === 'object') push(file.path ?? file.target)
865
- }
866
- return [...new Set(out)]
867
- }
868
-
869
- /** Code text of a code-execution tool call (argument name differs per Host). */
870
- export function codeTextOf(args) {
871
- if (!args || typeof args !== 'object') return undefined
872
- for (const key of ['code', 'script', 'source', 'python', 'ruby', 'js', 'command']) {
873
- if (typeof args[key] === 'string' && args[key].trim()) return args[key]
874
- }
875
- return undefined
876
- }
877
-
878
- /**
879
- * Decide which guard channel a tool call belongs to.
880
- *
881
- * Known write tools keep their dedicated path arguments; `publish` uses its copy
882
- * target; code tools are scanned statically; anything else that declares a path
883
- * argument and looks write-capable is inspected as `unknown` (only the two
884
- * high-risk destinations are denied for that channel).
885
- */
886
- export function toolWritePlan(toolName, args, options = {}) {
887
- const name = String(toolName ?? '').trim()
888
- if (!name || !args || typeof args !== 'object') return { channel: 'skip' }
889
- const lower = name.toLowerCase()
890
- const {
891
- writeToolNames = [...WRITE_TOOL_NAMES],
892
- publishToolNames = [...PUBLISH_TOOL_NAMES],
893
- codeToolNames = [...CODE_TOOL_NAMES],
894
- shellToolNames = [...SHELL_TOOL_NAMES],
895
- guardCodeTools = true,
896
- guardUnknownTools = true,
897
- guardPublish = true,
898
- schema,
899
- } = options
900
- // v0.7 (review S1): the plugin's own tools must always pass their own guard —
901
- // `longterm_approve` is the escape hatch the denial messages point at.
902
- if (SELF_TOOL_NAMES.has(lower)) return { channel: 'skip' }
903
- const matches = (list) => (Array.isArray(list) ? list.some((entry) => String(entry).toLowerCase() === lower) : false)
904
- if (matches(codeToolNames)) return guardCodeTools ? { channel: 'code' } : { channel: 'skip' }
905
- if (matches(shellToolNames)) return { channel: 'shell' }
906
- if (matches(publishToolNames)) {
907
- // `present` only declares files that already exist; it copies nothing.
908
- if (lower === 'present') return { channel: 'skip' }
909
- return guardPublish ? { channel: 'publish' } : { channel: 'skip' }
910
- }
911
- if (matches(writeToolNames)) return { channel: 'write' }
912
- if (!guardUnknownTools) return { channel: 'skip' }
913
- // v0.7 (review S4): a read-only tool stays read-only even when its description
914
- // mentions writing in a negation ("do not install libraries or create thumbnails").
915
- if (READ_ONLY_TOOL_PATTERN.test(lower)) return { channel: 'skip' }
916
- const description = typeof schema?.description === 'string' ? schema.description : ''
917
- if (!WRITE_HINT_PATTERN.test(`${lower} ${description}`)) return { channel: 'skip' }
918
- // v0.7 (review M1/S2/S3): only top-level arguments whose values actually look like
919
- // paths count; enum-like values (`this_session`, `@e3`, `#submit`, package ids) do not.
920
- const targets = collectPathTargets(args, { schema })
921
- if (targets.length === 0) return { channel: 'skip' }
922
- const parameters = schema?.parameters && typeof schema.parameters === 'object' ? schema.parameters : undefined
923
- const pathParams =
924
- parameters?.properties && typeof parameters.properties === 'object'
925
- ? Object.keys(parameters.properties).filter((key) => PATH_ARG_PATTERN.test(key))
926
- : []
927
- return { channel: 'unknown', pathParams }
928
- }
929
-
930
- async function readMarker(dir) {
931
- try {
932
- return JSON.parse(await readFile(join(dir, MARKER_FILE), 'utf8'))
933
- } catch {
934
- return undefined
935
- }
936
- }
937
-
938
- async function writeMarker(dir, sessionId, title, orphanedAt) {
939
- const payload = { sessionId: String(sessionId), title: title ?? '', updatedAt: Date.now() }
940
- if (Number.isFinite(orphanedAt) && orphanedAt > 0) payload.orphanedAt = orphanedAt
941
- try {
942
- await writeFile(join(dir, MARKER_FILE), JSON.stringify(payload, null, 2), 'utf8')
943
- } catch {
944
- // marker is best-effort; the folder still works without it
945
- }
946
- }
947
-
948
- /**
949
- * Delete marker-owned task folders whose owning session has been gone for `orphanDays`.
950
- *
951
- * @param {object} options
952
- * @param {Iterable<string>} options.roots workspace directories to scan
953
- * @param {string} [options.rootDirName] temp root name (default `_tmp`)
954
- * @param {number} options.orphanDays days after session deletion before removal (0 disables)
955
- * @param {boolean} [options.dryRun] report only, write/delete nothing
956
- * @param {Iterable<string>} [options.liveSessionIds] currently live sessions (never removed)
957
- * @param {Iterable<string>} [options.existingSessionIds] persisted sessions (never removed)
958
- * @param {number} [options.now] timestamp override (tests)
959
- * @param {(message: string) => void} [options.log] progress logger
960
- * @returns {Promise<object>} report
961
- */
962
- export async function cleanupOrphanedTempDirs({
963
- roots,
964
- rootDirName = DEFAULT_ROOT,
965
- orphanDays,
966
- dryRun = false,
967
- liveSessionIds = [],
968
- existingSessionIds = [],
969
- now = Date.now(),
970
- log = () => {},
971
- }) {
972
- const report = {
973
- dryRun,
974
- cutoff: now - orphanDays * DAY_MS,
975
- roots: [],
976
- markedOrphaned: [],
977
- deleted: [],
978
- kept: { live: 0, alive: 0, unmarked: 0, waiting: 0, error: 0 },
979
- }
980
- if (!(orphanDays > 0)) return report
981
- const live = new Set([...liveSessionIds].map((id) => String(id)))
982
- const known = new Set([...existingSessionIds].map((id) => String(id)))
983
- for (const id of live) known.add(id)
984
- const uniqueRoots = new Set([...roots].filter((root) => typeof root === 'string' && root.trim() !== ''))
985
-
986
- for (const root of uniqueRoots) {
987
- const tmpRoot = join(root, rootDirName)
988
- let entries
989
- try {
990
- entries = await readdir(tmpRoot, { withFileTypes: true })
991
- } catch {
992
- continue
993
- }
994
- report.roots.push(tmpRoot)
995
- for (const entry of entries) {
996
- if (!entry.isDirectory() || entry.isSymbolicLink()) continue
997
- const dir = join(tmpRoot, entry.name)
998
- try {
999
- const marker = await readMarker(dir)
1000
- if (!marker) {
1001
- report.kept.unmarked += 1
1002
- continue
1003
- }
1004
- const sessionId = String(marker.sessionId ?? '')
1005
- if (!sessionId) {
1006
- report.kept.unmarked += 1
1007
- continue
1008
- }
1009
- if (live.has(sessionId)) {
1010
- report.kept.live += 1
1011
- continue
1012
- }
1013
- if (known.has(sessionId)) {
1014
- report.kept.alive += 1
1015
- if (Number(marker.orphanedAt) > 0 && !dryRun) await writeMarker(dir, sessionId, marker.title, undefined)
1016
- continue
1017
- }
1018
- // Owning session no longer exists.
1019
- const orphanedAt = Number(marker.orphanedAt) || 0
1020
- if (orphanedAt <= 0) {
1021
- report.markedOrphaned.push(dir)
1022
- if (dryRun) {
1023
- report.kept.waiting += 1
1024
- log(`[dry-run] would mark orphaned ${dir}`)
1025
- } else {
1026
- await writeMarker(dir, sessionId, marker.title, now)
1027
- log(`marked orphaned ${dir}`)
1028
- }
1029
- continue
1030
- }
1031
- if (now - orphanedAt < orphanDays * DAY_MS) {
1032
- report.kept.waiting += 1
1033
- continue
1034
- }
1035
- if (dryRun) {
1036
- report.deleted.push({ path: dir, dryRun: true })
1037
- log(`[dry-run] would delete ${dir}`)
1038
- continue
1039
- }
1040
- await rm(dir, { recursive: true, force: true })
1041
- report.deleted.push({ path: dir })
1042
- log(`deleted ${dir}`)
1043
- } catch {
1044
- report.kept.error += 1
1045
- }
1046
- }
1047
- }
1048
- return report
1049
- }
1050
-
1051
- /** Resolve the DSH home directory (`DSH_HOME` override, else `~/.dsh`). */
1052
- export function resolveDshHome() {
1053
- const fromEnv = process.env.DSH_HOME && process.env.DSH_HOME.trim() ? process.env.DSH_HOME.trim() : ''
1054
- return fromEnv || join(homedir(), '.dsh')
1055
- }
1056
-
1057
- /** Best-effort fallback: collect session ids from the persisted session tree. */
1058
- async function scanPersistedSessionIds() {
1059
- const ids = new Set()
1060
- const home = resolveDshHome()
1061
- const roots = [join(home, 'sessions'), join(home, '_archived-sessions')]
1062
- const idPattern = /^(?:session-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
1063
- for (const root of roots) {
1064
- let workspaces
1065
- try {
1066
- workspaces = await readdir(root, { withFileTypes: true })
1067
- } catch {
1068
- continue
1069
- }
1070
- for (const workspace of workspaces) {
1071
- if (!workspace.isDirectory()) continue
1072
- const workspaceDir = join(root, workspace.name)
1073
- // Session directories live one level below; also cover a flat layout.
1074
- if (idPattern.test(workspace.name)) {
1075
- ids.add(workspace.name.replace(/^session-/, ''))
1076
- continue
1077
- }
1078
- let sessions
1079
- try {
1080
- sessions = await readdir(workspaceDir, { withFileTypes: true })
1081
- } catch {
1082
- continue
1083
- }
1084
- for (const session of sessions) {
1085
- if (!session.isDirectory()) continue
1086
- if (idPattern.test(session.name)) ids.add(session.name.replace(/^session-/, ''))
1087
- }
1088
- }
1089
- }
1090
- return ids
1091
- }
1092
-
1093
- /**
1094
- * Collect `sha256:` attachment ids from an arbitrary session-event payload.
1095
- *
1096
- * Attachment references are stored as `{ attachmentId: 'sha256:<hex>', ... }` inside
1097
- * `image` / `file` content blocks; walking the parsed event keeps this independent of
1098
- * where a block lives (user message, tool result, spliced inbox, …).
1099
- *
1100
- * @param {unknown} value parsed session event (or any nested JSON value)
1101
- * @param {Set<string>} [out] accumulator of hex hashes
1102
- * @param {number} [depth] recursion guard
1103
- * @returns {Set<string>}
1104
- */
1105
- export function collectAttachmentIds(value, out = new Set(), depth = 0) {
1106
- if (!value || depth > 24) return out
1107
- if (Array.isArray(value)) {
1108
- for (const item of value) collectAttachmentIds(item, out, depth + 1)
1109
- return out
1110
- }
1111
- if (typeof value !== 'object') return out
1112
- for (const [key, item] of Object.entries(value)) {
1113
- if (key === 'attachmentId' && typeof item === 'string') {
1114
- const match = ATTACHMENT_ID_PATTERN.exec(item)
1115
- if (match) out.add(match[1].toLowerCase())
1116
- continue
1117
- }
1118
- collectAttachmentIds(item, out, depth + 1)
1119
- }
1120
- return out
1121
- }
1122
-
1123
- /** Read the attachment ledger; a missing or unreadable file yields an empty ledger. */
1124
- async function readAttachmentLedger(path) {
1125
- try {
1126
- const parsed = JSON.parse(await readFile(path, 'utf8'))
1127
- if (parsed && typeof parsed === 'object' && parsed.sessions && typeof parsed.sessions === 'object') {
1128
- return {
1129
- version: ATTACHMENT_LEDGER_VERSION,
1130
- sessions: parsed.sessions,
1131
- lastSweepAt: Number(parsed.lastSweepAt) || 0,
1132
- }
1133
- }
1134
- } catch {
1135
- // missing or corrupt ledger: start from scratch
1136
- }
1137
- return { version: ATTACHMENT_LEDGER_VERSION, sessions: {}, lastSweepAt: 0 }
1138
- }
1139
-
1140
- /** Write the ledger atomically (temp file + rename), best-effort. */
1141
- async function writeAttachmentLedger(path, ledger) {
1142
- const temp = `${path}.tmp`
1143
- try {
1144
- await mkdir(dirname(path), { recursive: true })
1145
- await writeFile(temp, JSON.stringify(ledger), 'utf8')
1146
- await rename(temp, path)
1147
- } catch {
1148
- // ledger persistence is an optimization; a failed write only costs a rescan
1149
- }
1150
- }
1151
-
1152
- /**
1153
- * List every stored attachment blob.
1154
- * @param {string} attachmentsRoot attachment service root (default `<DSH_HOME>/attachments`)
1155
- * @returns {Promise<Array<{ hash: string, path: string, bytes: number, mtime: number }>>}
1156
- */
1157
- async function listAttachmentBlobs(attachmentsRoot) {
1158
- const objectsDir = join(attachmentsRoot, 'v1', 'objects')
1159
- /** @type {Array<{ hash: string, path: string, bytes: number, mtime: number }>} */
1160
- const blobs = []
1161
- let buckets
1162
- try {
1163
- buckets = await readdir(objectsDir, { withFileTypes: true })
1164
- } catch {
1165
- return blobs
1166
- }
1167
- for (const bucket of buckets) {
1168
- if (!bucket.isDirectory()) continue
1169
- const bucketDir = join(objectsDir, bucket.name)
1170
- let files
1171
- try {
1172
- files = await readdir(bucketDir, { withFileTypes: true })
1173
- } catch {
1174
- continue
1175
- }
1176
- for (const file of files) {
1177
- if (!file.isFile() || !/^[0-9a-f]{64}$/i.test(file.name)) continue
1178
- const full = join(bucketDir, file.name)
1179
- try {
1180
- const info = await stat(full)
1181
- blobs.push({ hash: file.name.toLowerCase(), path: full, bytes: info.size, mtime: info.mtimeMs })
1182
- } catch {
1183
- /* raced with a delete */
1184
- }
1185
- }
1186
- }
1187
- return blobs
1188
- }
1189
-
1190
- export function apply(ctx, config) {
1191
- const {
1192
- rootDirName,
1193
- includeSubagents,
1194
- maxNameLength,
1195
- orphanCleanupDays,
1196
- cleanupIntervalHours,
1197
- cleanupDryRun,
1198
- guardWorkspaceRoot,
1199
- requireApprovalOutsideTmp,
1200
- allowRootPatterns,
1201
- allowRootFiles,
1202
- commandGuard,
1203
- guardOutsideWorkspace,
1204
- publishGuard,
1205
- guardCodeTools,
1206
- guardUnknownTools,
1207
- writeToolNames,
1208
- publishToolNames,
1209
- codeToolNames,
1210
- shellToolNames,
1211
- outsideAllow: extraOutsideAllow,
1212
- publishBaseDir,
1213
- attachmentCleanup,
1214
- attachmentCleanupDays,
1215
- attachmentSweepOrphans,
1216
- attachmentsDir,
1217
- } = readConfig(config)
1218
- /** Directories outside the workspace that never need approval (DSH home, caches, temp). */
1219
- const outsideAllow = [...defaultOutsideAllow(resolveDshHome()), ...extraOutsideAllow]
1220
- const queues = new Map()
1221
- /** sessionId → approved long-term prefixes ({ prefix, reason, basis, approvedAt }[]). */
1222
- const approvals = new Map()
1223
- let sessionPersistence
1224
- let workspaceRegistry
1225
- try {
1226
- ctx.inject(['sessionPersistence'], (scoped) => {
1227
- sessionPersistence = scoped.sessionPersistence
1228
- })
1229
- } catch {
1230
- // fallback: the persisted session tree is scanned directly
1231
- }
1232
- try {
1233
- ctx.inject(['workspaceRegistry'], (scoped) => {
1234
- workspaceRegistry = scoped.workspaceRegistry
1235
- })
1236
- } catch {
1237
- // workspaceRegistry is optional; live sessions and the default directory still cover roots
1238
- }
1239
-
1240
- const cwdOf = (session) => {
1241
- try {
1242
- const dir = ctx.workingDirectory.get(session)
1243
- if (typeof dir === 'string' && dir) return dir
1244
- } catch {
1245
- // fall through to the header value
1246
- }
1247
- const headerCwd = session?.header?.cwd
1248
- return typeof headerCwd === 'string' && headerCwd ? headerCwd : undefined
1249
- }
1250
-
1251
- const titleOf = (session) => {
1252
- try {
1253
- const snapshot = ctx.sessionTitle.get(session)
1254
- if (snapshot?.title) return snapshot.title
1255
- } catch {
1256
- // title provider may be absent or the session may be detached
1257
- }
1258
- return undefined
1259
- }
1260
-
1261
- const isRelevant = (session) => includeSubagents || session?.header?.origin !== 'subagent'
1262
-
1263
- /**
1264
- * The root-entry guard only makes sense when the session is working at a workspace
1265
- * root. A session `cd`-ed into a subfolder (or a subagent started in a plugin dir)
1266
- * must not have its project files treated as "new workspace-root entries".
1267
- */
1268
- function isProtectedRoot(cwd) {
1269
- let workspaces = []
1270
- try {
1271
- workspaces = workspaceRegistry?.list() ?? []
1272
- } catch {
1273
- workspaces = []
1274
- }
1275
- if (workspaces.length > 0) return workspaces.some((workspace) => samePath(workspace?.path, cwd))
1276
- // Registry not ready: keep the historical strict behavior, default directory still counts.
1277
- try {
1278
- const defaultDir = ctx.workingDirectory.defaultDirectory
1279
- if (typeof defaultDir === 'string' && defaultDir) return samePath(defaultDir, cwd)
1280
- } catch {
1281
- // no default directory
1282
- }
1283
- return true
1284
- }
1285
-
1286
- const baseDir = (cwd) => join(cwd, rootDirName)
1287
-
1288
- // ── long-term approvals (per live session, in memory) ──────────────────────
1289
- const sessionKey = (session) => {
1290
- try {
1291
- return session?.id ? String(session.id) : ''
1292
- } catch {
1293
- return ''
1294
- }
1295
- }
1296
-
1297
- function approvedPrefixesFor(session) {
1298
- const id = sessionKey(session)
1299
- const list = id ? approvals.get(id) : undefined
1300
- return list ? list.map((entry) => entry.prefix) : []
1301
- }
1302
-
1303
- function registerApproval(session, prefix, { reason, basis }) {
1304
- const id = sessionKey(session)
1305
- if (!id) throw new Error('longterm_approve: session is unavailable')
1306
- const list = approvals.get(id) ?? []
1307
- const normalized = resolve(prefix)
1308
- if (!list.some((entry) => normalizeForCompare(entry.prefix) === normalizeForCompare(normalized))) {
1309
- list.push({ prefix: normalized, reason: reason ?? '', basis: basis ?? 'user_confirmed', approvedAt: Date.now() })
1310
- approvals.set(id, list)
1311
- console.info(`[session-task-tmpdir] longterm approved ${normalized} (session ${id})`)
1312
- }
1313
- return list
1314
- }
1315
-
1316
- async function isDir(path) {
1317
- try {
1318
- return (await stat(path)).isDirectory()
1319
- } catch {
1320
- return false
1321
- }
1322
- }
1323
-
1324
- async function findOwnedDir(cwd, sessionId) {
1325
- const root = baseDir(cwd)
1326
- let entries
1327
- try {
1328
- entries = await readdir(root, { withFileTypes: true })
1329
- } catch {
1330
- return undefined
1331
- }
1332
- for (const entry of entries) {
1333
- if (!entry.isDirectory()) continue
1334
- const dir = join(root, entry.name)
1335
- const marker = await readMarker(dir)
1336
- if (marker && String(marker.sessionId) === String(sessionId)) return dir
1337
- }
1338
- return undefined
1339
- }
1340
-
1341
- /**
1342
- * Pick a target path for `name`: reuse the folder owned by this session, adopt an
1343
- * empty unowned folder (removing it first when `removeEmpty` prepares a rename),
1344
- * otherwise append a numeric suffix.
1345
- */
1346
- async function chooseTarget(root, name, sessionId, { removeEmpty = false } = {}) {
1347
- let target = join(root, name)
1348
- let n = 2
1349
- for (;;) {
1350
- if (!(await isDir(target))) return target
1351
- const marker = await readMarker(target)
1352
- if (marker && sessionId !== undefined && String(marker.sessionId) === String(sessionId)) return target
1353
- const entries = await readdir(target).catch(() => [])
1354
- if (!marker && entries.length === 0) {
1355
- if (!removeEmpty) return target
1356
- await rm(target, { recursive: true, force: true }).catch(() => {})
1357
- return target
1358
- }
1359
- target = join(root, `${name} (${n++})`)
1360
- }
1361
- }
1362
-
1363
- async function createDir(session, sub) {
1364
- const cwd = cwdOf(session)
1365
- if (!cwd) throw new Error('session working directory is unavailable')
1366
- const title = titleOf(session)
1367
- const name = sanitizeTitle(title, maxNameLength) || `${FALLBACK_PREFIX}${String(session.id).slice(0, 8)}`
1368
- const root = baseDir(cwd)
1369
- await mkdir(root, { recursive: true })
1370
- // Reuse the folder this session already owns (e.g. a `sub` call after the first call)
1371
- const owned = await findOwnedDir(cwd, session.id)
1372
- const target = owned ?? (await chooseTarget(root, name, session.id))
1373
- await mkdir(target, { recursive: true })
1374
- await writeMarker(target, session.id, title ?? '')
1375
- const path = sub ? join(target, sanitizeTitle(sub, maxNameLength) || 'sub') : target
1376
- if (sub) await mkdir(path, { recursive: true })
1377
- return { path, title: title ?? '' }
1378
- }
1379
-
1380
- async function syncDir(session) {
1381
- const cwd = cwdOf(session)
1382
- if (!cwd) return
1383
- const title = titleOf(session)
1384
- if (!title) return
1385
- const name = sanitizeTitle(title, maxNameLength)
1386
- if (!name) return
1387
- const root = baseDir(cwd)
1388
- const owned = await findOwnedDir(cwd, session.id)
1389
- if (!owned) {
1390
- await createDir(session)
1391
- return
1392
- }
1393
- if (owned === join(root, name)) {
1394
- await writeMarker(owned, session.id, title)
1395
- return
1396
- }
1397
- const target = await chooseTarget(root, name, session.id, { removeEmpty: true })
1398
- if (target === owned) return
1399
- try {
1400
- await rename(owned, target)
1401
- } catch (error) {
1402
- // A locked file can block the rename on Windows; keep the old folder and its marker.
1403
- console.warn('[session-task-tmpdir] rename failed:', error?.message ?? error)
1404
- return
1405
- }
1406
- await writeMarker(target, session.id, title)
1407
- }
1408
-
1409
- function enqueue(session) {
1410
- const id = String(session.id)
1411
- const previous = queues.get(id) ?? Promise.resolve()
1412
- const next = previous
1413
- .then(() => syncDir(session))
1414
- .catch((error) => console.warn('[session-task-tmpdir] sync failed:', error?.message ?? error))
1415
- .finally(() => {
1416
- if (queues.get(id) === next) queues.delete(id)
1417
- })
1418
- queues.set(id, next)
1419
- }
1420
-
1421
- // Title change (user rename and automatic title regeneration both append session/title).
1422
- ctx.effect(() =>
1423
- ctx.on('session/event', (session, event) => {
1424
- if (event?.type !== 'session/title') return
1425
- if (!session || !isRelevant(session)) return
1426
- enqueue(session)
1427
- }),
1428
- )
1429
-
1430
- // A resumed session may already carry a title; materialize the folder on creation.
1431
- ctx.effect(() =>
1432
- ctx.on('session/created', (session) => {
1433
- if (!session || !isRelevant(session)) return
1434
- enqueue(session)
1435
- }),
1436
- )
1437
-
1438
- // Drop per-session long-term approvals once the session is gone.
1439
- ctx.effect(() =>
1440
- ctx.on('session/disposed', (session) => {
1441
- const id = sessionKey(session)
1442
- if (id) approvals.delete(id)
1443
- }),
1444
- )
1445
-
1446
- // ── orphan cleanup ─────────────────────────────────────────────────────────
1447
- let cleaning = false
1448
-
1449
- async function loadPersistenceSnapshots() {
1450
- if (sessionPersistence && typeof sessionPersistence.list === 'function') {
1451
- try {
1452
- return await sessionPersistence.list()
1453
- } catch {
1454
- // fall through to the directory scan
1455
- }
1456
- }
1457
- return undefined
1458
- }
1459
-
1460
- async function collectPersistedSessionIds() {
1461
- const snapshots = await loadPersistenceSnapshots()
1462
- if (snapshots) return snapshots.map((snapshot) => String(snapshot?.header?.id ?? '')).filter(Boolean)
1463
- return [...(await scanPersistedSessionIds())]
1464
- }
1465
-
1466
- // ── attachment cleanup (v0.6) ───────────────────────────────────────────────
1467
- // The attachment store is content-addressed and never garbage collected by the Host,
1468
- // so deleting a conversation leaves its blobs behind forever. Every cleanup tick we
1469
- // record the attachment ids each *stored* session references (ledger), stamp the
1470
- // moment a session disappears, and only once that stamp is older than
1471
- // `attachmentCleanupDays` delete the blobs no surviving session references.
1472
- const attachmentsRoot = attachmentsDir
1473
- const attachmentLedgerPath = join(resolveDshHome(), 'data', ATTACHMENT_LEDGER_FILE)
1474
- const attachmentGcLogPath = join(resolveDshHome(), 'data', ATTACHMENT_GC_LOG_FILE)
1475
-
1476
- /** Read one stored session through the persistence service and collect its attachment ids. */
1477
- async function readSessionAttachmentIds(sessionId) {
1478
- if (!sessionPersistence || typeof sessionPersistence.open !== 'function') return undefined
1479
- let handle
1480
- try {
1481
- handle = await sessionPersistence.open(sessionId, 'read')
1482
- } catch {
1483
- return undefined
1484
- }
1485
- const ids = new Set()
1486
- try {
1487
- let offset = 0
1488
- for (let page = 0; page < ATTACHMENT_READ_PAGE_LIMIT; page += 1) {
1489
- const result = await handle.read(offset, ATTACHMENT_READ_PAGE_SIZE)
1490
- const events = Array.isArray(result?.events) ? result.events : []
1491
- if (events.length === 0) break
1492
- for (const event of events) collectAttachmentIds(event, ids)
1493
- const lastSeq = Number(events[events.length - 1]?.seq)
1494
- if (!Number.isFinite(lastSeq) || lastSeq < offset) break
1495
- offset = lastSeq + 1
1496
- if (events.length < ATTACHMENT_READ_PAGE_SIZE) break
1497
- }
1498
- } catch {
1499
- // torn or unreadable tail: keep whatever was collected so far
1500
- } finally {
1501
- try {
1502
- await handle.close()
1503
- } catch {
1504
- /* already closed */
1505
- }
1506
- }
1507
- return ids
1508
- }
1509
-
1510
- /**
1511
- * Delete attachment blobs whose owning session has been gone for `attachmentCleanupDays`,
1512
- * plus (optionally) blobs no stored session references and that are at least that old.
1513
- */
1514
- async function runAttachmentCleanup(trigger, { dryRun = cleanupDryRun } = {}) {
1515
- if (!attachmentCleanup) return { skipped: 'disabled' }
1516
- const snapshots = await loadPersistenceSnapshots()
1517
- if (!snapshots) return { skipped: 'sessionPersistence-unavailable' }
1518
- if (snapshots.length === 0) return { skipped: 'no-stored-sessions' }
1519
- const now = Date.now()
1520
- const liveSessionIds = new Set()
1521
- try {
1522
- for (const session of ctx.sessions.list()) liveSessionIds.add(String(session.id))
1523
- } catch {
1524
- /* sessions unavailable this tick */
1525
- }
1526
- const ledger = await readAttachmentLedger(attachmentLedgerPath)
1527
- const alive = new Set()
1528
- const referenced = new Set()
1529
- let rescanned = 0
1530
- let scannedFailures = 0
1531
- for (const snapshot of snapshots) {
1532
- const id = String(snapshot?.header?.id ?? '')
1533
- if (!id) continue
1534
- alive.add(id)
1535
- const revision = String(snapshot?.revision ?? '')
1536
- const entry = ledger.sessions[id]
1537
- let hashes
1538
- if (entry && entry.revision === revision && Array.isArray(entry.hashes)) {
1539
- hashes = entry.hashes
1540
- } else {
1541
- const scanned = await readSessionAttachmentIds(id)
1542
- if (!scanned) {
1543
- scannedFailures += 1
1544
- if (entry && Array.isArray(entry.hashes)) hashes = entry.hashes
1545
- else continue
1546
- } else {
1547
- hashes = [...scanned]
1548
- ledger.sessions[id] = { revision, hashes, scannedAt: now }
1549
- rescanned += 1
1550
- }
1551
- }
1552
- for (const hash of hashes) referenced.add(hash)
1553
- }
1554
-
1555
- // ── safety interlocks (portability) ───────────────────────────────────────
1556
- // The layout and the attachment-id vocabulary are Host-owned. On another platform
1557
- // (HarmonyOS / mobile / a future store version) either may differ; sweeping then
1558
- // must fail closed instead of treating "nothing referenced" as "everything stale".
1559
- const blobs = await listAttachmentBlobs(attachmentsRoot)
1560
- if (blobs.length === 0) {
1561
- return { skipped: 'no-attachment-objects', attachmentsRoot }
1562
- }
1563
- if (referenced.size === 0) {
1564
- return {
1565
- skipped: 'no-attachment-references',
1566
- objects: blobs.length,
1567
- storedSessions: alive.size,
1568
- rescanned,
1569
- scanFailures: scannedFailures,
1570
- }
1571
- }
1572
-
1573
- // Stamp sessions that vanished since the previous tick.
1574
- let markedOrphaned = 0
1575
- for (const [id, entry] of Object.entries(ledger.sessions)) {
1576
- if (alive.has(id) || liveSessionIds.has(id)) continue
1577
- if (!entry) continue
1578
- if (!(Number(entry.orphanedAt) > 0)) {
1579
- entry.orphanedAt = now
1580
- markedOrphaned += 1
1581
- }
1582
- }
1583
-
1584
- const graceDays = attachmentCleanupDays
1585
- const due = new Map()
1586
- for (const [id, entry] of Object.entries(ledger.sessions)) {
1587
- if (!entry || alive.has(id) || liveSessionIds.has(id)) continue
1588
- const orphanedAt = Number(entry.orphanedAt) || 0
1589
- if (!(orphanedAt > 0)) continue
1590
- if (now - orphanedAt < graceDays * DAY_MS) continue
1591
- due.set(id, entry)
1592
- }
1593
-
1594
- const deleted = []
1595
- let freedBytes = 0
1596
- let skippedRecent = 0
1597
- let skippedReferenced = 0
1598
- const drop = async (hash, reason) => {
1599
- const blobPath = join(attachmentsRoot, 'v1', 'objects', hash.slice(0, 2), hash)
1600
- let info
1601
- try {
1602
- info = await stat(blobPath)
1603
- } catch {
1604
- return false
1605
- }
1606
- if (now - info.mtimeMs < ATTACHMENT_MIN_AGE_MS) {
1607
- skippedRecent += 1
1608
- return false
1609
- }
1610
- if (!dryRun) {
1611
- try {
1612
- await rm(blobPath, { force: true })
1613
- } catch {
1614
- return false
1615
- }
1616
- }
1617
- deleted.push({ hash, bytes: info.size, reason })
1618
- freedBytes += info.size
1619
- return true
1620
- }
1621
-
1622
- for (const entry of due.values()) {
1623
- for (const hash of entry.hashes ?? []) {
1624
- if (referenced.has(hash)) {
1625
- skippedReferenced += 1
1626
- continue
1627
- }
1628
- await drop(hash, 'session-deleted')
1629
- }
1630
- }
1631
-
1632
- const known = new Set()
1633
- for (const entry of Object.values(ledger.sessions)) {
1634
- for (const hash of entry?.hashes ?? []) known.add(hash)
1635
- }
1636
- let sweptOrphans = 0
1637
- if (attachmentSweepOrphans) {
1638
- for (const blob of blobs) {
1639
- if (referenced.has(blob.hash) || known.has(blob.hash)) continue
1640
- if (now - blob.mtime < graceDays * DAY_MS) continue
1641
- if (await drop(blob.hash, 'unreferenced')) sweptOrphans += 1
1642
- }
1643
- }
1644
-
1645
- if (!dryRun) {
1646
- for (const id of due.keys()) delete ledger.sessions[id]
1647
- ledger.lastSweepAt = now
1648
- await writeAttachmentLedger(attachmentLedgerPath, ledger)
1649
- if (deleted.length > 0) {
1650
- try {
1651
- await appendFile(
1652
- attachmentGcLogPath,
1653
- `${JSON.stringify({ at: new Date(now).toISOString(), trigger, deleted })}\n`,
1654
- 'utf8',
1655
- )
1656
- } catch {
1657
- /* audit log is best-effort */
1658
- }
1659
- }
1660
- }
1661
-
1662
- const report = {
1663
- dryRun,
1664
- storedSessions: alive.size,
1665
- objects: blobs.length,
1666
- rescanned,
1667
- scanFailures: scannedFailures,
1668
- referencedBlobs: referenced.size,
1669
- markedOrphaned,
1670
- dueSessions: due.size,
1671
- deleted: deleted.length,
1672
- freedBytes,
1673
- sweptOrphans,
1674
- skippedRecent,
1675
- skippedReferenced,
1676
- }
1677
- if (report.deleted > 0 || report.markedOrphaned > 0) {
1678
- console.info(
1679
- `[session-task-tmpdir] attachments(${trigger})${dryRun ? ' dry-run' : ''}: ` +
1680
- `deleted ${report.deleted} (${(freedBytes / 1048576).toFixed(1)} MB), ` +
1681
- `marked ${report.markedOrphaned}, due sessions ${report.dueSessions}, ` +
1682
- `referenced ${report.referencedBlobs}, rescanned ${report.rescanned}`,
1683
- )
1684
- }
1685
- return report
1686
- }
1687
-
1688
- async function runCleanup(trigger, { dryRun = cleanupDryRun, withAttachments = true } = {}) {
1689
- if (cleaning || !(orphanCleanupDays > 0)) return undefined
1690
- cleaning = true
1691
- try {
1692
- const roots = new Set()
1693
- try {
1694
- const defaultDir = ctx.workingDirectory.defaultDirectory
1695
- if (typeof defaultDir === 'string' && defaultDir) roots.add(defaultDir)
1696
- } catch {
1697
- /* no default directory */
1698
- }
1699
- const liveSessionIds = []
1700
- try {
1701
- for (const session of ctx.sessions.list()) {
1702
- liveSessionIds.push(String(session.id))
1703
- const dir = cwdOf(session)
1704
- if (dir) roots.add(dir)
1705
- }
1706
- } catch {
1707
- /* sessions unavailable this tick */
1708
- }
1709
- try {
1710
- for (const workspace of workspaceRegistry?.list() ?? []) {
1711
- if (workspace?.path) roots.add(workspace.path)
1712
- }
1713
- } catch {
1714
- /* registry unavailable this tick */
1715
- }
1716
- const existingSessionIds = await collectPersistedSessionIds()
1717
- const report = await cleanupOrphanedTempDirs({
1718
- roots,
1719
- rootDirName,
1720
- orphanDays: orphanCleanupDays,
1721
- dryRun,
1722
- liveSessionIds,
1723
- existingSessionIds,
1724
- log: (message) => console.info(`[session-task-tmpdir] ${message}`),
1725
- })
1726
- if (
1727
- report.deleted.length > 0 ||
1728
- report.markedOrphaned.length > 0 ||
1729
- report.kept.error > 0
1730
- ) {
1731
- console.info(
1732
- `[session-task-tmpdir] cleanup(${trigger})${report.dryRun ? ' dry-run' : ''}: ` +
1733
- `deleted ${report.deleted.length}, marked ${report.markedOrphaned.length}, ` +
1734
- `kept live ${report.kept.live} / alive ${report.kept.alive} / waiting ${report.kept.waiting} / ` +
1735
- `unmarked ${report.kept.unmarked} / errors ${report.kept.error}`,
1736
- )
1737
- }
1738
- // Attachment store sweep (v0.6): same tick, same 7-day semantics.
1739
- if (withAttachments) {
1740
- try {
1741
- report.attachments = await runAttachmentCleanup(trigger, { dryRun })
1742
- } catch (error) {
1743
- console.warn('[session-task-tmpdir] attachment cleanup failed:', error?.message ?? error)
1744
- report.attachments = { error: String(error?.message ?? error) }
1745
- }
1746
- }
1747
- return report
1748
- } catch (error) {
1749
- console.warn('[session-task-tmpdir] cleanup failed:', error?.message ?? error)
1750
- return undefined
1751
- } finally {
1752
- cleaning = false
1753
- }
1754
- }
1755
-
1756
- if (orphanCleanupDays > 0) {
1757
- ctx.effect(() => {
1758
- const startupTimer = setTimeout(() => {
1759
- void runCleanup('startup')
1760
- }, STARTUP_CLEANUP_DELAY_MS)
1761
- const interval = setInterval(() => {
1762
- void runCleanup('interval')
1763
- }, cleanupIntervalHours * 3_600_000)
1764
- return () => {
1765
- clearTimeout(startupTimer)
1766
- clearInterval(interval)
1767
- }
1768
- }, 'session-task-tmpdir: cleanup schedule')
1769
- }
1770
-
1771
- // ── prompt convention + tool ────────────────────────────────────────────────
1772
- ctx.effect(() =>
1773
- ctx.systemPrompt.context({
1774
- name: 'session-task-tmpdir',
1775
- order: 900,
1776
- text: [
1777
- '## Task temp folder (session-task-tmpdir)',
1778
- '',
1779
- `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.`,
1780
- '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.',
1781
- '',
1782
- '### Long-term files need the user’s approval first',
1783
- '',
1784
- '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 → `' +
1785
- rootDirName +
1786
- '/` and must NOT trigger a question.',
1787
- `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:`,
1788
- '- A. 不长期保存',
1789
- '- B. 工作区根目录保存',
1790
- `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.`,
1791
- 'Do not write anything until the user answers.',
1792
- '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).',
1793
- '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.',
1794
- '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.',
1795
- `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.`,
1796
- '',
1797
- `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)'}.`,
1798
- '',
1799
- '### What the write guard covers (v0.7)',
1800
- '',
1801
- 'The rule is enforced at the tool layer, not only in this text. Checked channels:',
1802
- '- `write` / `edit` path arguments;',
1803
- '- `publish` delivery copies (`source` → `target`, e.g. HarmonyOS `Download/<package>/`); `present` only displays an existing file and is not a write;',
1804
- '- shell tools (`pwsh` / `bash`): literal absolute paths in commands that create something;',
1805
- '- code-execution tools (`python` / `node` / …): write statements paired with path literals (static best-effort; dynamically built paths are not guaranteed);',
1806
- '- any other tool whose schema declares path arguments: a new workspace-root entry or a destination outside the workspace is denied.',
1807
- '',
1808
- `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).`,
1809
- ].join('\n'),
1810
- }),
1811
- )
1812
-
1813
- ctx.effect(() =>
1814
- ctx.tools.register({
1815
- name: 'task_tmpdir',
1816
- 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.`,
1817
- parameters: {
1818
- type: 'object',
1819
- properties: {
1820
- sub: { type: 'string', description: 'Optional subdirectory under the task temp directory.' },
1821
- },
1822
- additionalProperties: false,
1823
- },
1824
- output: {
1825
- schema: {
1826
- type: 'object',
1827
- properties: {
1828
- path: { type: 'string' },
1829
- title: { type: 'string' },
1830
- },
1831
- required: ['path', 'title'],
1832
- },
1833
- render: (_args, value) => [{ type: 'text', text: String(value?.path ?? '') }],
1834
- },
1835
- async execute(args, exec) {
1836
- const agent = exec?.agent
1837
- const session = agent ? ctx.sessions.get(agent.id) : undefined
1838
- if (!session) throw new Error('task_tmpdir: no live session for this tool call')
1839
- const result = await createDir(session, args?.sub)
1840
- return result
1841
- },
1842
- }),
1843
- )
1844
-
1845
- // Long-term destination approval. The model may only call this after the user
1846
- // picked a location (multiple-choice question) or after the task itself named it.
1847
- ctx.effect(() =>
1848
- ctx.tools.register({
1849
- name: 'longterm_approve',
1850
- description:
1851
- '登记「本次会话已获用户同意的长期保存落点」。用户明确同意长期保存(或任务里已指定位置)后调用;' +
1852
- `登记后 write/edit、shell 命令、publish 交付、python 等代码工具才能写该目录(工作区内或工作区外都可以),` +
1853
- `否则会被拒绝并提示先问用户。临时产物不要用它,直接用 task_tmpdir 写 ${rootDirName}/<会话标题>/。`,
1854
- parameters: {
1855
- type: 'object',
1856
- properties: {
1857
- path: { type: 'string', description: '用户指定/同意的目录绝对路径(传文件路径也行,会自动取所在目录)。' },
1858
- reason: { type: 'string', description: '为什么属于长期保存(一句话,用于日志)。' },
1859
- basis: {
1860
- type: 'string',
1861
- enum: ['user_confirmed', 'task_designated'],
1862
- description: 'user_confirmed=用户刚在选择题里同意长期保存;task_designated=用户在任务里明确指定了该位置。',
1863
- },
1864
- },
1865
- required: ['path'],
1866
- additionalProperties: false,
1867
- },
1868
- output: {
1869
- schema: {
1870
- type: 'object',
1871
- properties: {
1872
- approved: { type: 'boolean' },
1873
- path: { type: 'string' },
1874
- basis: { type: 'string' },
1875
- approvedPrefixes: { type: 'array', items: { type: 'string' } },
1876
- },
1877
- required: ['approved', 'path'],
1878
- },
1879
- render: (_args, value) => [
1880
- { type: 'text', text: `approved: ${String(value?.path ?? '')}` },
1881
- ],
1882
- },
1883
- async execute(args, exec) {
1884
- const agent = exec?.agent
1885
- const session = agent ? ctx.sessions.get(agent.id) : undefined
1886
- if (!session) throw new Error('longterm_approve: no live session for this tool call')
1887
- const cwd = cwdOf(session)
1888
- if (!cwd) throw new Error('longterm_approve: session working directory is unavailable')
1889
- const raw = typeof args?.path === 'string' ? args.path.trim() : ''
1890
- if (!raw) throw new Error('longterm_approve: path 不能为空')
1891
- const expanded = expandTildePath(raw)
1892
- const abs = isAbsolute(expanded) ? resolve(expanded) : resolve(cwd, expanded)
1893
- const tmpRoot = baseDir(cwd)
1894
- if (samePath(abs, tmpRoot) || pathInside(tmpRoot, abs)) {
1895
- throw new Error(`longterm_approve: ${rootDirName}/ 是临时目录,不需要也不允许登记`)
1896
- }
1897
- if (isScratchPath(abs, rootDirName)) {
1898
- throw new Error(`longterm_approve: 路径包含 ${rootDirName}/ 临时目录段,不需要也不允许登记`)
1899
- }
1900
- // v0.7 (review A9): registering the workspace root itself would whitelist the
1901
- // whole workspace, so it is refused like a filesystem root.
1902
- if (samePath(abs, cwd)) {
1903
- throw new Error('longterm_approve: 不能登记会话工作区根目录本身,请指定工作区内的具体子目录(或工作区外的目录)')
1904
- }
1905
- const insideWorkspace = pathInside(cwd, abs)
1906
- if (!insideWorkspace) {
1907
- // v0.7: a destination outside the workspace (e.g. HarmonyOS
1908
- // `Download/<package>/`) can be registered too, but never a filesystem
1909
- // root, a whole drive or the user's home directory.
1910
- const segments = abs.replace(/[\\/]+$/, '').split(/[\\/]+/).filter(Boolean)
1911
- let fsRoot
1912
- try {
1913
- fsRoot = parse(abs).root
1914
- } catch {
1915
- fsRoot = undefined
1916
- }
1917
- if ((fsRoot && samePath(abs, fsRoot)) || samePath(abs, homedir()) || segments.length < 2) {
1918
- throw new Error('longterm_approve: 不能登记磁盘根目录、用户主目录或层级过浅的目录,请指定具体文件夹')
1919
- }
1920
- }
1921
- const basis = args?.basis === 'task_designated' ? 'task_designated' : 'user_confirmed'
1922
- let directory = abs
1923
- try {
1924
- if (existsSync(abs)) {
1925
- if (!statSync(abs).isDirectory()) directory = dirname(abs)
1926
- } else if (FILE_EXTENSION_PATTERN.test(basename(abs))) {
1927
- // v0.7 (review A9): a not-yet-created file path registers its directory,
1928
- // otherwise the next file in the same folder would still be denied.
1929
- directory = dirname(abs)
1930
- }
1931
- } catch {
1932
- // keep the passed path
1933
- }
1934
- const list = registerApproval(session, directory, { reason: args?.reason, basis })
1935
- return {
1936
- approved: true,
1937
- path: directory,
1938
- basis,
1939
- approvedPrefixes: list.map((entry) => entry.prefix),
1940
- }
1941
- },
1942
- }),
1943
- )
1944
-
1945
- // Manual cleanup trigger (also handy for verifying the scheduled pass).
1946
- ctx.effect(() =>
1947
- ctx.tools.register({
1948
- 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, and (v0.6) the attachment store reclaims the blobs of sessions deleted more than ${attachmentCleanupDays} days ago; everything else is reported as kept. Pass dryRun to only report.`,
1949
- parameters: {
1950
- type: 'object',
1951
- properties: {
1952
- dryRun: { type: 'boolean', description: 'Only report what would be marked or deleted.' },
1953
- attachments: { type: 'boolean', description: 'Also sweep the attachment store (default true).' },
1954
- },
1955
- additionalProperties: false,
1956
- },
1957
- output: {
1958
- schema: {
1959
- type: 'object',
1960
- properties: {
1961
- disabled: { type: 'boolean' },
1962
- dryRun: { type: 'boolean' },
1963
- deleted: { type: 'number' },
1964
- markedOrphaned: { type: 'number' },
1965
- kept: { type: 'object' },
1966
- attachments: { type: 'object' },
1967
- },
1968
- },
1969
- render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
1970
- },
1971
- async execute(args) {
1972
- const withAttachments = args?.attachments !== false
1973
- const report = await runCleanup('manual', { dryRun: args?.dryRun === true, withAttachments })
1974
- if (!report) return { disabled: true, dryRun: false, deleted: 0, markedOrphaned: 0, kept: {} }
1975
- const value = {
1976
- disabled: false,
1977
- dryRun: report.dryRun,
1978
- deleted: report.deleted.length,
1979
- markedOrphaned: report.markedOrphaned.length,
1980
- kept: report.kept,
1981
- paths: report.deleted.map((entry) => entry.path),
1982
- }
1983
- if (report.attachments) {
1984
- const a = report.attachments
1985
- value.attachments = a.skipped || a.error
1986
- ? a
1987
- : {
1988
- dryRun: Boolean(a.dryRun),
1989
- deleted: a.deleted ?? 0,
1990
- freedMb: Number(((a.freedBytes ?? 0) / 1048576).toFixed(1)),
1991
- dueSessions: a.dueSessions ?? 0,
1992
- storedSessions: a.storedSessions ?? 0,
1993
- objects: a.objects ?? 0,
1994
- referencedBlobs: a.referencedBlobs ?? 0,
1995
- markedOrphaned: a.markedOrphaned ?? 0,
1996
- sweptOrphans: a.sweptOrphans ?? 0,
1997
- skippedRecent: a.skippedRecent ?? 0,
1998
- skippedReferenced: a.skippedReferenced ?? 0,
1999
- }
2000
- }
2001
- return value
2002
- },
2003
- }),
2004
- )
2005
-
2006
- // ── write guard (v0.5 root rules, v0.7 capability channels) ────────────────
2007
- // Scratch files keep the v1 rules (temp-named files in the working-directory root
2008
- // and files directly under `<rootDirName>/` are denied). Long-term artifacts
2009
- // additionally require a session approval: `write`/`edit`, shell commands,
2010
- // delivery copies made by `publish`, embedded code runtimes and other tools that
2011
- // declare path arguments may not create anything outside `<rootDirName>/` (or
2012
- // outside the workspace) until the model has asked the user and registered the
2013
- // chosen directory with `longterm_approve`.
2014
- if (guardWorkspaceRoot || requireApprovalOutsideTmp) {
2015
- ctx.effect(
2016
- () =>
2017
- ctx.tools.guard((execution) => {
2018
- try {
2019
- if (!execution) return undefined
2020
- const toolName = String(execution.name ?? '')
2021
- const args = execution.arguments && typeof execution.arguments === 'object' ? execution.arguments : undefined
2022
- if (!args) return undefined
2023
- const agent = execution.agent
2024
- if (!agent) return undefined
2025
- const session = ctx.sessions.get(agent.id)
2026
- if (!session) return undefined
2027
- const cwd = cwdOf(session)
2028
- if (!cwd) return undefined
2029
- let schema = execution.schema
2030
- if (!schema || typeof schema !== 'object') {
2031
- try {
2032
- schema = ctx.tools.get(toolName, agent)
2033
- } catch {
2034
- schema = undefined
2035
- }
2036
- }
2037
- const plan = toolWritePlan(toolName, args, {
2038
- writeToolNames,
2039
- publishToolNames,
2040
- codeToolNames,
2041
- shellToolNames,
2042
- guardCodeTools,
2043
- guardUnknownTools,
2044
- guardPublish: publishGuard !== 'off',
2045
- schema,
2046
- })
2047
- if (plan.channel === 'skip') return undefined
2048
-
2049
- // v0.7 (review M5): only the v1 "workspace-root" rules depend on the session
2050
- // working directory being a registered workspace root. Destinations outside
2051
- // the workspace are checked even when the session `cd`-ed into a subfolder.
2052
- const protectedRoot = isProtectedRoot(cwd)
2053
- const approvedPrefixes = approvedPrefixesFor(session)
2054
- const classifyOptions = {
2055
- rootDirName,
2056
- allowRootPatterns,
2057
- allowRootFiles,
2058
- approvedPrefixes,
2059
- outsideAllow,
2060
- requireApprovalOutsideTmp,
2061
- guardOutsideWorkspace,
2062
- }
2063
- const deny = (label, reason) => {
2064
- console.info(`[session-task-tmpdir] ${label} denied: ${reason}`)
2065
- return reason
2066
- }
2067
- const outsideWarn = (label, abs) => {
2068
- console.info(`[session-task-tmpdir] ${label} (warn): ${abs}`)
2069
- }
2070
-
2071
- // write/edit: scratch rules first (v0.5), then the long-term classification
2072
- if (plan.channel === 'write') {
2073
- const targetPath = firstWriteTarget(args)
2074
- if (!targetPath) return undefined
2075
- if (guardWorkspaceRoot && protectedRoot) {
2076
- const scratchReason = workspaceRootGuardReason(targetPath, cwd, rootDirName)
2077
- if (scratchReason) return deny(`${toolName} guard`, scratchReason)
2078
- }
2079
- const verdict = classifyWriteTarget(targetPath, cwd, classifyOptions)
2080
- if (verdict.kind === 'inside-longterm') {
2081
- if (!protectedRoot) return undefined
2082
- return deny('longterm guard', verdict.reason)
2083
- }
2084
- if (verdict.kind === 'outside') {
2085
- if (guardOutsideWorkspace === 'warn') {
2086
- outsideWarn('outside guard', verdict.abs)
2087
- return undefined
2088
- }
2089
- if (guardOutsideWorkspace === 'off') return undefined
2090
- return deny('outside guard', outsideWriteDenialReason(verdict.abs, { rootDirName }))
2091
- }
2092
- return undefined
2093
- }
2094
-
2095
- // publish: the tool copies a finished artifact into a delivery folder
2096
- if (plan.channel === 'publish') {
2097
- const publishBase =
2098
- typeof publishBaseDir === 'string' && publishBaseDir.trim() ? resolve(cwd, publishBaseDir.trim()) : undefined
2099
- for (const target of publishWriteTargets(args)) {
2100
- const verdict = classifyWriteTarget(target, cwd, {
2101
- ...classifyOptions,
2102
- baseDir: publishBase,
2103
- })
2104
- if (verdict.kind !== 'inside-longterm' && verdict.kind !== 'outside') continue
2105
- if (verdict.kind === 'inside-longterm' && !protectedRoot) continue
2106
- if (publishGuard === 'warn') {
2107
- outsideWarn('publish guard', verdict.abs)
2108
- continue
2109
- }
2110
- const reason =
2111
- verdict.kind === 'outside'
2112
- ? outsideWriteDenialReason(verdict.abs, { rootDirName, action: '发布' })
2113
- : `${verdict.reason}(发布目标:${verdict.abs})`
2114
- return deny('publish guard', `publish 会把文件复制到长期位置:${reason}`)
2115
- }
2116
- return undefined
2117
- }
2118
-
2119
- // code tools (python/node/…): best-effort static scan of write statements
2120
- if (plan.channel === 'code') {
2121
- const code = codeTextOf(args)
2122
- if (!code) return undefined
2123
- const reason = codeToolGuardReason(code, cwd, {
2124
- ...classifyOptions,
2125
- guardOutsideWorkspace,
2126
- skipInside: !protectedRoot,
2127
- })
2128
- if (reason) return deny('code guard', reason)
2129
- return undefined
2130
- }
2131
-
2132
- // shell tools: literal-path scan of commands that create something
2133
- if (plan.channel === 'shell') {
2134
- if (commandGuard === 'off') return undefined
2135
- const command = typeof args.command === 'string' ? args.command : undefined
2136
- if (!command) return undefined
2137
- const commandBase =
2138
- typeof args.workdir === 'string' && args.workdir.trim() ? resolve(cwd, args.workdir) : cwd
2139
- const reason = longtermCommandGuardReason(command, cwd, {
2140
- ...classifyOptions,
2141
- baseDir: commandBase,
2142
- skipInside: !protectedRoot,
2143
- })
2144
- if (!reason) return undefined
2145
- if (commandGuard === 'warn') {
2146
- console.info(`[session-task-tmpdir] command guard (warn) ${reason}`)
2147
- return undefined
2148
- }
2149
- return deny('command guard', reason)
2150
- }
2151
-
2152
- // unknown but write-capable tools: only the two high-risk destinations
2153
- if (plan.channel === 'unknown') {
2154
- for (const target of collectPathTargets(args, { schema })) {
2155
- const verdict = classifyWriteTarget(target, cwd, classifyOptions)
2156
- if (verdict.kind === 'outside') {
2157
- if (guardOutsideWorkspace === 'warn') {
2158
- outsideWarn('outside guard', verdict.abs)
2159
- continue
2160
- }
2161
- if (guardOutsideWorkspace === 'off') continue
2162
- return deny('outside guard', outsideWriteDenialReason(verdict.abs, { rootDirName }))
2163
- }
2164
- if (verdict.kind === 'inside-longterm' && protectedRoot && samePath(dirname(verdict.abs), resolve(cwd))) {
2165
- return deny('longterm guard', verdict.reason)
2166
- }
2167
- }
2168
- return undefined
2169
- }
2170
- return undefined
2171
- } catch {
2172
- return undefined
2173
- }
2174
- }),
2175
- 'session-task-tmpdir: write guard',
2176
- )
2177
- }
2178
- }
1
+ import { existsSync, mkdirSync, statSync, writeFileSync } from 'node:fs'
2
+ import { appendFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
3
+ import { homedir, tmpdir } from 'node:os'
4
+ import { basename, dirname, isAbsolute, join, parse, 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
+ * v0.7 closes the write channels that used to bypass the guard:
27
+ * - every call is classified by capability (`toolWritePlan`): `write`/`edit`, shell
28
+ * tools, code-execution tools (`python`, `node`, …), delivery tools (`publish`) and
29
+ * unknown tools that declare path arguments; `present` is display-only;
30
+ * - destinations outside the workspace are classified as well — DSH's own home,
31
+ * caches and the OS temp directory are allowed, anything else is long-term
32
+ * (`outsideAllow` extends that list);
33
+ * - shell parsing is platform aware (drive paths on Windows, `/`-rooted paths on
34
+ * HarmonyOS/POSIX Hosts) and covers POSIX create verbs;
35
+ * - `longterm_approve` may register a directory outside the workspace (never a
36
+ * filesystem root or the home directory itself).
37
+ *
38
+ * v0.8 closes the last leak in the cleanup chain: a folder created under
39
+ * `<rootDirName>/` by a plain `write`/shell/code command (instead of `task_tmpdir`)
40
+ * has no marker, so the sweep treated it as "not ours" and never removed it. While
41
+ * allowing such a write the guard now stamps the target folder with the acting
42
+ * session's id — no guessing, because the guard already knows both the target path and
43
+ * the session.
44
+ *
45
+ * Cleanup (default: 7 days after the owning session is deleted):
46
+ * - once a day every registered workspace's `<rootDirName>` is scanned;
47
+ * - a folder whose session still exists (live or persisted) is always kept;
48
+ * - a folder whose session is gone is stamped `orphanedAt` on first sight;
49
+ * - once `orphanedAt` is older than `orphanCleanupDays`, the folder is deleted.
50
+ * Folders without our marker are never touched.
51
+ *
52
+ * Attachment garbage collection (v0.6), same schedule and grace period:
53
+ * - the Host attachment store (`<DSH_HOME>/attachments`) is content-addressed and never
54
+ * garbage collected, so deleting a conversation used to leave its blobs on disk forever;
55
+ * - every tick the ledger `<DSH_HOME>/data/session-tmpdir-attachments.json` records which
56
+ * attachment ids each stored session references (read through `sessionPersistence`, so
57
+ * no log format is assumed); only a changed revision is re-read;
58
+ * - a session that disappears is stamped `orphanedAt`; after `attachmentCleanupDays` the
59
+ * blobs it alone referenced are deleted (any blob still referenced is always kept);
60
+ * - blobs nobody references and older than the grace period are swept as well, which
61
+ * reclaims the historical leftovers of sessions deleted before this feature existed;
62
+ * - every deletion is appended to `session-tmpdir-attachments-gc.jsonl`, and a blob
63
+ * written within the last hour is never touched.
64
+ */
65
+
66
+ const MARKER_FILE = '.dsh-task.json'
67
+ const DEFAULT_ROOT = '_tmp'
68
+ const DEFAULT_MAX_NAME = 60
69
+ const DEFAULT_ORPHAN_DAYS = 7
70
+ const DEFAULT_CLEANUP_HOURS = 24
71
+ const STARTUP_CLEANUP_DELAY_MS = 60_000
72
+ const FALLBACK_PREFIX = 'session-'
73
+ const DAY_MS = 86_400_000
74
+
75
+ // ── attachment garbage collection (v0.6) ────────────────────────────────────
76
+ /** Ledger file (under `<DSH_HOME>/data/`) recording which attachments each session used. */
77
+ const ATTACHMENT_LEDGER_FILE = 'session-tmpdir-attachments.json'
78
+ /** Append-only audit log of every attachment the collector deleted. */
79
+ const ATTACHMENT_GC_LOG_FILE = 'session-tmpdir-attachments-gc.jsonl'
80
+ const ATTACHMENT_LEDGER_VERSION = 1
81
+ /** `attachmentId` values look like `sha256:<64 lowercase hex>`. */
82
+ const ATTACHMENT_ID_PATTERN = /^sha256:([0-9a-f]{64})$/i
83
+ /** Never delete a blob written this recently — it may belong to a message not yet persisted. */
84
+ const ATTACHMENT_MIN_AGE_MS = 3_600_000
85
+ /** Upper bound on read pages per session, so one corrupt log cannot hang the sweep. */
86
+ const ATTACHMENT_READ_PAGE_LIMIT = 200
87
+ /** Events per read page: keeps peak memory bounded on very long sessions. */
88
+ const ATTACHMENT_READ_PAGE_SIZE = 500
89
+ /** Tool names whose path arguments create or overwrite a file. */
90
+ const WRITE_TOOL_NAMES = new Set(['write', 'edit', 'multi_edit', 'apply_patch', 'str_replace_editor'])
91
+ /** Tool names that run a shell command (their write targets must be parsed from text). */
92
+ const SHELL_TOOL_NAMES = new Set(['pwsh', 'bash', 'sh', 'zsh', 'shell', 'terminal', 'cmd', 'powershell'])
93
+ /** Tool names that execute code in a Host-embedded runtime; their writes are scanned statically. */
94
+ const CODE_TOOL_NAMES = new Set([
95
+ 'python',
96
+ 'python3',
97
+ 'py',
98
+ 'node',
99
+ 'run_code',
100
+ 'execute_code',
101
+ 'code_interpreter',
102
+ 'ipython',
103
+ 'ruby',
104
+ 'perl',
105
+ ])
106
+ /** Delivery tools: `publish` (HarmonyOS DSHM) copies a file into a delivery folder; `present` only shows it. */
107
+ const PUBLISH_TOOL_NAMES = new Set(['publish', 'present'])
108
+ /** Argument names that can carry a file or directory target. */
109
+ const PATH_ARG_PATTERN =
110
+ /^(?:file_?paths?|paths?|files?|target|targets|target_?path|destination|dest|dst|dest_?path|to|output|output_?path|output_?dir|out|out_?path|dir|directory|directory_?path|folder|save_?path|save|filename|file_?name|location|locations|download_?dir|upload_?dir)$/i
111
+ /** Source-only path arguments (the read side of a copy/publish). */
112
+ const SOURCE_PATH_ARG_PATTERN = /^(?:source|src|from|origin|input|input_?path|source_?path)$/i
113
+ /** Tool name/description words that indicate a write-capable tool. */
114
+ const WRITE_HINT_PATTERN =
115
+ /\b(?:write|writes|writefile|save|create|export|publish|present|download|upload|copy|move|rename|delete|remove|mkdir|install|render|convert|recalculate|generate|produce|dump|store|merge|split|unzip|unpack|extract|replace|patch|append|edit|output)\b/i
116
+ /** Read-only tool names: skipped even when their description mentions a write in a negation. */
117
+ const READ_ONLY_TOOL_PATTERN = /^(?:read|list|get|show|view|check|status|query|search|find|glob|grep|count|stat)(?:[_\-.]|$)/i
118
+ /** The plugin's own tools must always pass their own guard (approval must not self-lock). */
119
+ const SELF_TOOL_NAMES = new Set(['task_tmpdir', 'longterm_approve', 'tmp_cleanup'])
120
+ /** Windows device names that are never files on disk. */
121
+ const WINDOWS_DEVICE_PATTERN = /^(?:nul|con|prn|aux|clock\$|com[0-9]|lpt[0-9])$/i
122
+ /** `scheme://...` tokens are stripped before shell path scanning (a URL contains `s:/`). */
123
+ const URL_PATTERN = /[A-Za-z][A-Za-z0-9+.\-]*:\/\/[^\s'"`]*/g
124
+ /** File names that are scratch artifacts wherever they land. */
125
+ const TEMP_FILE_PATTERNS = [/^_tmp/i, /^tmp_/i, /\.tmp$/i, /\.temp$/i, /\.part$/i, /^~\$/]
126
+ const DEFAULT_ALLOW_ROOT_PATTERNS = ['dsh-*']
127
+ const DEFAULT_ALLOW_ROOT_FILES = ['.dsh-standing-rules.md']
128
+ const DEFAULT_COMMAND_GUARD = 'deny'
129
+ const DEFAULT_PUBLISH_GUARD = 'deny'
130
+ /** Command text that can create a directory/file; used before scanning for paths (v0.7: POSIX verbs). */
131
+ const CREATE_VERB_PATTERN =
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
+ /** Redirection source shared by the global form. */
134
+ const REDIRECT_SOURCE =
135
+ '(?:^|[\\s;&|])(?:>>|\\d?>>?)\\s*(?:"([^"]+)"|\'([^\']+)\'|([^\\s;&|]+))'
136
+ /** Every redirection target in a command (v0.7: all of them, not only the first). */
137
+ const REDIRECT_ALL_PATTERN = new RegExp(REDIRECT_SOURCE, 'g')
138
+ /** Windows absolute path tokens inside a command string (not part of a URL). */
139
+ const WIN_ABS_PATH_PATTERN = /(?<![A-Za-z0-9])([A-Za-z]:[\\/][^\s'"`,;|&)}\]>]+)/g
140
+ /** POSIX absolute path tokens inside a command string (HarmonyOS/POSIX Hosts). */
141
+ const POSIX_ABS_PATH_PATTERN = /(?:^|[\s'"`(=])(\/(?!\/)[^\s'"`,;|&)}\]<>]+)/g
142
+ /** v0.8 claim-on-write: relative `<rootDirName>/<dir>` mentions in a shell command. */
143
+ const TMP_RELATIVE_PATTERN = /(?:^|[\s'"`(=,;|&])(\.{0,2}[\\/]?_tmp[\\/][^\s'"`,;|&)}\]>]+)/g
144
+ /** v0.8: shell verbs that create a directory (so an exact `<root>/<dir>` target is a folder). */
145
+ const CREATE_DIR_HINT_PATTERN =
146
+ /(?:^|[\s;|&(])(?:mkdir|md|ni)\b|\bNew-Item\b[^|;]*(?:-ItemType\s+Directory|\bDirectory\b)|\bgit\s+clone\b|\bCopy-Item\b[^|;]*-Recurse/i
147
+ /** Pseudo paths that are never created on disk. */
148
+ const DEVICE_PATH_PATTERN = /^\/(?:dev\/(?:null|zero|stdin|stdout|stderr|tty|urandom|random|shm)|proc|sys)(?:\/|$)/
149
+ /** `_tmp`-like directory segments that always mean "scratch". */
150
+ const SCRATCH_SEGMENT_NAMES = new Set(['_tmp'])
151
+ /** Write signals inside a code string (Python/JS/Ruby best-effort static scan). */
152
+ const CODE_WRITE_SIGNAL =
153
+ /(?:open\s*\([^()]*,\s*['"][^'"]*[wax+][^'"]*['"]|\.write_text\s*\(|\.write_bytes\s*\(|shutil\.(?:copy|copy2|copyfile|move|copytree|rmtree)|os\.(?:replace|rename|remove|unlink|mkdir|makedirs|rmdir|removedirs|mknod|symlink|link)|json\.dump\s*\(|pickle\.dump\s*\(|\.to_csv\s*\(|\.to_excel\s*\(|\.to_json\s*\(|\.to_pickle\s*\(|\.to_parquet\s*\(|\.savefig\s*\(|\.save\s*\(|imwrite\s*\(|np\.save\w*\s*\(|writeFile(?:Sync)?\s*\(|appendFile(?:Sync)?\s*\(|createWriteStream\s*\(|writeTextFile\s*\(|fs\.(?:copyFile\w*|rename\w*|unlink\w*|mkdir\w*|rm\w*|writeFile\w*|appendFile\w*)|\.mkdir\w*\s*\(|\.rmdir\w*\s*\(|mkdirSync\s*\()/g
154
+ /** String literals that look like file paths inside code (absolute, or relative with a separator/known extension). */
155
+ const CODE_PATH_LITERAL =
156
+ /(['"])((?:\/[^'"\n]{1,400}|[A-Za-z]:[\\/][^'"\n]{1,400}|\.{1,2}[\\/][^'"\n]{1,400}|[A-Za-z0-9_.\-]+[\\/][^'"\n]{1,400}|[A-Za-z0-9_.\-]+\.(?:md|txt|json|jsonl|csv|tsv|xlsx|docx|pptx|pdf|png|jpe?g|gif|webp|mp4|mov|mp3|wav|html?|xml|ya?ml|zip|tar|gz|py|js|ts|mjs|sh)))\1/g
157
+ /** Distance (chars) within which a write signal and a path literal are treated as one statement. */
158
+ const CODE_SIGNAL_WINDOW = 300
159
+ /** v0.7: Windows desktop vs HarmonyOS/POSIX device. */
160
+ const IS_WINDOWS = process.platform === 'win32'
161
+
162
+ export const name = 'session-task-tmpdir'
163
+
164
+ export const inject = ['sessions', 'sessionTitle', 'workingDirectory', 'systemPrompt', 'tools']
165
+
166
+ /** Strip characters that are illegal in Windows/POSIX directory names and bound the length. */
167
+ export function sanitizeTitle(raw, maxLength = DEFAULT_MAX_NAME) {
168
+ let text = String(raw ?? '')
169
+ .normalize('NFC')
170
+ // eslint-disable-next-line no-control-regex
171
+ .replace(/[\\/:*?"<>|\u0000-\u001f]+/g, '-')
172
+ .replace(/\s+/g, ' ')
173
+ .trim()
174
+ // Windows: names may not end with a dot or space
175
+ text = text.replace(/^[.\s]+|[.\s]+$/g, '')
176
+ if (!text) return ''
177
+ if (text.length > maxLength) text = text.slice(0, maxLength).trim()
178
+ text = text.replace(/^[.\s]+|[.\s]+$/g, '')
179
+ return text === '.' || text === '..' ? '' : text
180
+ }
181
+
182
+ function readConfig(config) {
183
+ const c = config && typeof config === 'object' ? config : {}
184
+ const rootDirName = typeof c.rootDirName === 'string' && c.rootDirName.trim() ? c.rootDirName.trim() : DEFAULT_ROOT
185
+ const includeSubagents = c.includeSubagents === true
186
+ const maxNameLength = Number.isInteger(c.maxNameLength) && c.maxNameLength > 0 ? c.maxNameLength : DEFAULT_MAX_NAME
187
+ const orphanCleanupDays = Number.isFinite(c.orphanCleanupDays) && c.orphanCleanupDays >= 0 ? c.orphanCleanupDays : DEFAULT_ORPHAN_DAYS
188
+ const cleanupIntervalHours = Number.isFinite(c.cleanupIntervalHours) && c.cleanupIntervalHours >= 1 ? c.cleanupIntervalHours : DEFAULT_CLEANUP_HOURS
189
+ const cleanupDryRun = c.cleanupDryRun === true
190
+ const attachmentCleanup = c.attachmentCleanup !== false
191
+ const attachmentCleanupDays =
192
+ Number.isFinite(c.attachmentCleanupDays) && c.attachmentCleanupDays >= 0 ? c.attachmentCleanupDays : orphanCleanupDays
193
+ const attachmentSweepOrphans = c.attachmentSweepOrphans !== false
194
+ const attachmentsDir =
195
+ typeof c.attachmentsDir === 'string' && c.attachmentsDir.trim() ? c.attachmentsDir.trim() : join(resolveDshHome(), 'attachments')
196
+ const guardWorkspaceRoot = c.guardWorkspaceRoot !== false
197
+ const requireApprovalOutsideTmp = c.requireApprovalOutsideTmp !== false
198
+ const allowRootPatterns = toStringList(c.allowRootPatterns, DEFAULT_ALLOW_ROOT_PATTERNS)
199
+ const allowRootFiles = toStringList(c.allowRootFiles, DEFAULT_ALLOW_ROOT_FILES)
200
+ const commandGuard = ['deny', 'warn', 'off'].includes(c.commandGuard) ? c.commandGuard : DEFAULT_COMMAND_GUARD
201
+ // ── v0.7: write-channel coverage ─────────────────────────────────────────
202
+ /** Guard writes that land outside the workspace (deny | warn | off). */
203
+ const guardOutsideWorkspace = ['deny', 'warn', 'off'].includes(c.guardOutsideWorkspace)
204
+ ? c.guardOutsideWorkspace
205
+ : 'deny'
206
+ /** Guard delivery tools (`publish`/`present` with a copy target): deny | warn | off. */
207
+ const publishGuard = ['deny', 'warn', 'off'].includes(c.publishGuard) ? c.publishGuard : DEFAULT_PUBLISH_GUARD
208
+ /** Statically scan code-execution tools (python/node) for file writes. */
209
+ const guardCodeTools = c.guardCodeTools !== false
210
+ /** Also inspect tools the plugin does not know by name, using their schema/description. */
211
+ const guardUnknownTools = c.guardUnknownTools !== false
212
+ /** Extra tool names per channel, appended to the built-in sets. */
213
+ const extraWriteTools = toStringList(c.writeToolNames, [])
214
+ const extraPublishTools = toStringList(c.publishToolNames, [])
215
+ const extraCodeTools = toStringList(c.codeToolNames, [])
216
+ /** Extra absolute directories that may be written outside the workspace (globs). */
217
+ const outsideAllow = toStringList(c.outsideAllow, [])
218
+ /** Base directory used to resolve a relative `publish` target (e.g. HarmonyOS `Download/`). */
219
+ const publishBaseDir = typeof c.publishBaseDir === 'string' && c.publishBaseDir.trim() ? c.publishBaseDir.trim() : undefined
220
+ return {
221
+ rootDirName,
222
+ includeSubagents,
223
+ maxNameLength,
224
+ orphanCleanupDays,
225
+ cleanupIntervalHours,
226
+ cleanupDryRun,
227
+ guardWorkspaceRoot,
228
+ requireApprovalOutsideTmp,
229
+ allowRootPatterns,
230
+ allowRootFiles,
231
+ commandGuard,
232
+ guardOutsideWorkspace,
233
+ publishGuard,
234
+ guardCodeTools,
235
+ guardUnknownTools,
236
+ writeToolNames: [...new Set([...WRITE_TOOL_NAMES, ...extraWriteTools])],
237
+ publishToolNames: [...new Set([...PUBLISH_TOOL_NAMES, ...extraPublishTools])],
238
+ codeToolNames: [...new Set([...CODE_TOOL_NAMES, ...extraCodeTools])],
239
+ shellToolNames: [...SHELL_TOOL_NAMES],
240
+ outsideAllow,
241
+ publishBaseDir,
242
+ attachmentCleanup,
243
+ attachmentCleanupDays,
244
+ attachmentSweepOrphans,
245
+ attachmentsDir,
246
+ }
247
+ }
248
+
249
+ /** Accept a string or an array of strings as a config list, falling back to `fallback`. */
250
+ function toStringList(value, fallback) {
251
+ if (typeof value === 'string' && value.trim()) return [value.trim()]
252
+ if (Array.isArray(value)) {
253
+ const list = value.filter((item) => typeof item === 'string' && item.trim()).map((item) => item.trim())
254
+ if (list.length > 0) return list
255
+ }
256
+ return [...fallback]
257
+ }
258
+
259
+ /** Path comparison: case-insensitive on Windows, exact and separator-normalized elsewhere. */
260
+ function samePath(a, b) {
261
+ if (typeof a !== 'string' || typeof b !== 'string') return false
262
+ const normalize = (value) => {
263
+ const text = resolve(value).replace(/[\\/]+$/, '')
264
+ return IS_WINDOWS ? text.replace(/\\/g, '/').toLowerCase() : text
265
+ }
266
+ return normalize(a) === normalize(b)
267
+ }
268
+
269
+ /**
270
+ * Reject scratch-file writes that land in the wrong place:
271
+ * temp-looking names directly in the working-directory root, or any file directly
272
+ * under `<cwd>/<rootDirName>/` instead of a session subfolder.
273
+ *
274
+ * @param {string} targetPath the write/edit `file_path` argument (absolute or relative to cwd)
275
+ * @param {string} cwd the session working directory
276
+ * @param {string} [rootDirName] temp root name (default `_tmp`)
277
+ * @returns {string | undefined} denial reason for the tool guard, or undefined to allow
278
+ */
279
+ export function workspaceRootGuardReason(targetPath, cwd, rootDirName = DEFAULT_ROOT) {
280
+ if (typeof targetPath !== 'string' || targetPath.trim() === '') return undefined
281
+ if (typeof cwd !== 'string' || cwd.trim() === '') return undefined
282
+ let abs
283
+ try {
284
+ abs = isAbsolute(targetPath) ? targetPath : resolve(cwd, targetPath)
285
+ } catch {
286
+ return undefined
287
+ }
288
+ const name = basename(abs)
289
+ if (!name) return undefined
290
+ if (samePath(dirname(abs), cwd) && TEMP_FILE_PATTERNS.some((pattern) => pattern.test(name))) {
291
+ return (
292
+ `工作区根目录不能放临时文件(${name})。请先调用 task_tmpdir 获取 ` +
293
+ `${rootDirName}/<会话标题>/ 的准确路径,把临时文件写进那个目录。`
294
+ )
295
+ }
296
+ if (samePath(dirname(abs), join(cwd, rootDirName))) {
297
+ return (
298
+ `${rootDirName}/ 根目录不能直接放文件(${name})。请先调用 task_tmpdir,` +
299
+ `把文件写入 ${rootDirName}/<会话标题>/ 子目录。`
300
+ )
301
+ }
302
+ return undefined
303
+ }
304
+
305
+ // ── long-term destination guard (v0.5) ─────────────────────────────────────────
306
+
307
+ /**
308
+ * Normalized path used for comparisons: forward slashes on Windows (case folded),
309
+ * untouched on POSIX where `\` is a legal filename character (v0.7, review M10).
310
+ */
311
+ function normalizeForCompare(target) {
312
+ const text = resolve(target).replace(/[\\/]+$/, '')
313
+ return IS_WINDOWS ? text.replace(/\\/g, '/').toLowerCase() : text
314
+ }
315
+
316
+ /**
317
+ * True when `child` is `parent` or lives inside it (case-insensitive, separator
318
+ * normalized). v0.7: uses `/` on every platform, so the check also works on
319
+ * HarmonyOS/POSIX Hosts where `resolve()` never emits a backslash.
320
+ */
321
+ export function pathInside(parent, child) {
322
+ if (typeof parent !== 'string' || typeof child !== 'string') return false
323
+ if (!parent.trim() || !child.trim()) return false
324
+ const p = normalizeForCompare(parent)
325
+ const c = normalizeForCompare(child)
326
+ return c === p || c.startsWith(`${p}/`)
327
+ }
328
+
329
+ /** 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
332
+ const base = resolve(cwd)
333
+ const target = resolve(abs)
334
+ if (!(normalizeForCompare(base) === normalizeForCompare(target) || pathInside(base, target))) return undefined
335
+ if (normalizeForCompare(base) === normalizeForCompare(target)) return ''
336
+ const rest = target.slice(base.replace(/[\\/]+$/, '').length).replace(/^[\\/]+/, '')
337
+ const [first] = rest.split(/[\\/]+/).filter(Boolean)
338
+ return first ?? ''
339
+ }
340
+
341
+ /** Simple case-insensitive glob matcher (`*` and `?` only). */
342
+ export function globMatch(name, patterns) {
343
+ const text = String(name ?? '')
344
+ for (const raw of patterns ?? []) {
345
+ const pattern = String(raw ?? '').trim()
346
+ if (!pattern) continue
347
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
348
+ try {
349
+ if (new RegExp(`^${escaped}$`, 'i').test(text)) return true
350
+ } catch {
351
+ // an unusable pattern never matches
352
+ }
353
+ }
354
+ return false
355
+ }
356
+
357
+ /**
358
+ * Decide whether a `write`/`edit` target outside the temp root may be written.
359
+ *
360
+ * Rules (v0.5):
361
+ * - under `<cwd>/<rootDirName>/` → allowed (scratch);
362
+ * - under an approved long-term prefix → allowed (session registered it via longterm_approve);
363
+ * - root-level file → allowed only when explicitly allow-listed;
364
+ * - first segment matching allowRootPatterns → allowed (plugin source trees by default);
365
+ * - anything else → denied with the "ask the user first" protocol.
366
+ *
367
+ * @returns {string | undefined} denial reason, or undefined to allow
368
+ */
369
+ export function longtermGuardReason(targetPath, cwd, options = {}) {
370
+ const {
371
+ rootDirName = DEFAULT_ROOT,
372
+ allowRootPatterns = DEFAULT_ALLOW_ROOT_PATTERNS,
373
+ allowRootFiles = DEFAULT_ALLOW_ROOT_FILES,
374
+ approvedPrefixes = [],
375
+ requireApprovalOutsideTmp = true,
376
+ } = options
377
+ if (!requireApprovalOutsideTmp) return undefined
378
+ if (typeof targetPath !== 'string' || targetPath.trim() === '') return undefined
379
+ if (typeof cwd !== 'string' || cwd.trim() === '') return undefined
380
+ let abs
381
+ try {
382
+ abs = isAbsolute(targetPath) ? targetPath : resolve(cwd, targetPath)
383
+ } catch {
384
+ return undefined
385
+ }
386
+ const base = resolve(cwd)
387
+ if (!pathInside(base, abs)) return undefined
388
+ const tmpRoot = join(base, rootDirName)
389
+ if (pathInside(tmpRoot, abs)) return undefined
390
+ if (approvedPrefixes.some((prefix) => pathInside(prefix, abs))) return undefined
391
+ if (samePath(dirname(abs), base)) {
392
+ const name = basename(abs)
393
+ if (allowRootFiles.some((entry) => entry.toLowerCase() === name.toLowerCase())) return undefined
394
+ if (globMatch(name, allowRootPatterns)) return undefined
395
+ return (
396
+ `工作区根目录不能新建/修改条目(${name})。若这份内容需要长期保存:先用 ask_user_question 征求用户意见,` +
397
+ `用户同意后用 longterm_approve 登记用户指定的目录再写;用户不同意或属于临时产物 → 用 task_tmpdir 写到 ` +
398
+ `${rootDirName}/<会话标题>/。`
399
+ )
400
+ }
401
+ const first = firstSegmentUnder(base, abs)
402
+ if (!first) return undefined
403
+ if (globMatch(first, allowRootPatterns)) return undefined
404
+ return (
405
+ `「${first}」不在本次会话已批准的长期落点里。若这份内容需要长期保存:先用 ask_user_question 征求用户意见,` +
406
+ `用户同意后调用 longterm_approve 登记用户指定的目录再写;用户不同意或属于临时产物 → 用 task_tmpdir 写到 ` +
407
+ `${rootDirName}/<会话标题>/。`
408
+ )
409
+ }
410
+
411
+ /**
412
+ * Best-effort guard for shell tools: when a command may create something, scan its
413
+ * literal absolute Windows paths. Any not-yet-existing path inside the workspace that is
414
+ * neither scratch nor approved is denied. Paths that already exist are left alone (they are
415
+ * usually sources for Copy-Item or files being edited) — this keeps false positives low.
416
+ *
417
+ * @returns {string | undefined} denial reason, or undefined to allow
418
+ */
419
+ export function longtermCommandGuardReason(command, workspaceRoot, options = {}) {
420
+ const {
421
+ rootDirName = DEFAULT_ROOT,
422
+ allowRootPatterns = DEFAULT_ALLOW_ROOT_PATTERNS,
423
+ allowRootFiles = DEFAULT_ALLOW_ROOT_FILES,
424
+ approvedPrefixes = [],
425
+ outsideAllow = [],
426
+ requireApprovalOutsideTmp = true,
427
+ guardOutsideWorkspace = 'deny',
428
+ skipInside = false,
429
+ baseDir,
430
+ pathExists = (target) => existsSync(target),
431
+ platform = process.platform,
432
+ } = options
433
+ if (!requireApprovalOutsideTmp) return undefined
434
+ if (typeof command !== 'string' || command.trim() === '') return undefined
435
+ if (typeof workspaceRoot !== 'string' || workspaceRoot.trim() === '') return undefined
436
+ // v0.7 (review M2): every redirect target counts, not only the first, and `>>` is
437
+ // parsed as one token instead of leaving a second `>` behind. Quoted text such as
438
+ // `Write-Host "1 > 0"` and device names (`NUL`, `$null`) are not real targets.
439
+ const redirectTokens = new Set()
440
+ for (const match of command.matchAll(REDIRECT_ALL_PATTERN)) {
441
+ const token = match[1] ?? match[2] ?? match[3]
442
+ if (!token) continue
443
+ const cleaned = token.replace(/["'`]+$/, '')
444
+ if (!cleaned || /^>+$/.test(cleaned)) continue
445
+ if (!looksLikePathValue(cleaned) && !FILE_EXTENSION_PATTERN.test(cleaned)) continue
446
+ redirectTokens.add(token)
447
+ }
448
+ const hasRedirect = redirectTokens.size > 0
449
+ if (!hasRedirect && !CREATE_VERB_PATTERN.test(command)) return undefined
450
+ const base = resolve(workspaceRoot)
451
+ const resolveBase = typeof baseDir === 'string' && baseDir.trim() ? resolve(baseDir) : base
452
+ // v0.7 (review M3): strip `scheme://…` first — `https://` contains `s:/`, which the
453
+ // Windows drive-path pattern would otherwise treat as a directory.
454
+ const scanText = command.replace(URL_PATTERN, ' ')
455
+ const pathPattern = platform === 'win32' ? WIN_ABS_PATH_PATTERN : POSIX_ABS_PATH_PATTERN
456
+ const tokens = new Set([...redirectTokens])
457
+ for (const match of scanText.matchAll(pathPattern)) tokens.add(match[1])
458
+ const classifyOptions = {
459
+ rootDirName,
460
+ allowRootPatterns,
461
+ allowRootFiles,
462
+ approvedPrefixes,
463
+ outsideAllow,
464
+ requireApprovalOutsideTmp,
465
+ guardOutsideWorkspace,
466
+ }
467
+ for (const raw of tokens) {
468
+ if (!raw) continue
469
+ const cleaned = String(raw).replace(/["'`]+$/, '')
470
+ let abs
471
+ try {
472
+ const expanded = expandTildePath(cleaned)
473
+ abs = isAbsolute(expanded) ? resolve(expanded) : resolve(resolveBase, expanded)
474
+ } catch {
475
+ continue
476
+ }
477
+ if (isDevicePath(abs)) continue
478
+ // v0.8 claim-on-write: report every resolved target so the caller can attribute
479
+ // unmarked `<rootDirName>/<dir>/` folders to the acting session.
480
+ if (typeof options.onTarget === 'function') {
481
+ try {
482
+ options.onTarget(abs)
483
+ } catch {
484
+ // a reporting callback never changes the verdict
485
+ }
486
+ }
487
+ const isRedirectTarget = redirectTokens.has(raw)
488
+ const verdict = classifyWriteTarget(abs, base, classifyOptions)
489
+ 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
494
+ if (verdict.kind === 'outside') {
495
+ if (guardOutsideWorkspace === 'warn') {
496
+ console.info(`[session-task-tmpdir] command guard (warn): ${abs}`)
497
+ continue
498
+ }
499
+ return outsideWriteDenialReason(abs, { rootDirName, action: '执行这条命令' })
500
+ }
501
+ // inside the workspace but not approved / not scratch
502
+ if (skipInside) continue
503
+ const first = firstSegmentUnder(base, abs)
504
+ if (samePath(dirname(abs), base)) {
505
+ return (
506
+ `命令会新建工作区根目录条目「${basename(abs)}」(${abs})。若需要长期保存:先用 ask_user_question 征求用户意见,` +
507
+ `同意后 longterm_approve 登记目录再执行;临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
508
+ )
509
+ }
510
+ return (
511
+ `命令会新建工作区里的「${first || basename(abs)}」(${abs}),它不在本次会话已批准的长期落点里。` +
512
+ `若需要长期保存:先用 ask_user_question 征求用户意见,同意后 longterm_approve 登记目录再执行;` +
513
+ `临时产物请写到 ${rootDirName}/<会话标题>/(先 task_tmpdir 取路径)。`
514
+ )
515
+ }
516
+ return undefined
517
+ }
518
+
519
+ // ── v0.7: write-channel resolution (capability based, not a fixed tool list) ──
520
+
521
+ /** Expand a leading `~` to the current user's home directory. */
522
+ function expandTildePath(value) {
523
+ if (typeof value !== 'string' || !value.trim()) return value
524
+ const text = value.trim()
525
+ if (text === '~') return homedir()
526
+ if (text.startsWith('~/') || text.startsWith('~\\')) return join(homedir(), text.slice(2))
527
+ return text
528
+ }
529
+
530
+ /** Forward-slash, lower-cased (on Windows) form used by path globs. */
531
+ function slashedPath(value) {
532
+ const text = String(value).replace(/\\/g, '/').replace(/\/+$/, '')
533
+ return IS_WINDOWS ? text.toLowerCase() : text
534
+ }
535
+
536
+ /** True for `/dev/null`-style pseudo paths and Windows device names (never on disk). */
537
+ function isDevicePath(abs) {
538
+ if (typeof abs !== 'string') return false
539
+ if (DEVICE_PATH_PATTERN.test(String(abs).replace(/\\/g, '/'))) return true
540
+ if (!IS_WINDOWS) return false
541
+ const name = basename(abs).trim()
542
+ if (/^\$null$/i.test(name)) return true
543
+ return WINDOWS_DEVICE_PATTERN.test(name.replace(/\$\d*$/, ''))
544
+ }
545
+
546
+ /** True when a path lives under the OS temp directory (`os.tmpdir()`, `/tmp`, `/var/tmp`). */
547
+ export function isSystemTempPath(abs) {
548
+ if (typeof abs !== 'string' || !abs.trim()) return false
549
+ const tempDirs = [tmpdir(), '/tmp', '/var/tmp', '/dev/shm']
550
+ return tempDirs.some((dir) => dir && pathInside(dir, abs))
551
+ }
552
+
553
+ /** True when any path segment is a scratch root (`_tmp`, configured root name). */
554
+ export function isScratchPath(targetPath, rootDirName = DEFAULT_ROOT) {
555
+ if (typeof targetPath !== 'string' || !targetPath.trim()) return false
556
+ const segments = String(targetPath)
557
+ .replace(/\\/g, '/')
558
+ .split('/')
559
+ .filter(Boolean)
560
+ const names = new Set([...SCRATCH_SEGMENT_NAMES].map((name) => name.toLowerCase()))
561
+ if (typeof rootDirName === 'string' && rootDirName.trim()) names.add(rootDirName.trim().toLowerCase())
562
+ return segments.some((segment) => names.has(segment.toLowerCase()))
563
+ }
564
+
565
+ /**
566
+ * Glob match for absolute path patterns: `*` stays inside one segment, `**` crosses
567
+ * segments. Patterns may start with `~`; a pattern ending in `/**` also matches the
568
+ * directory itself. Used for the `outsideAllow` list.
569
+ */
570
+ export function pathGlobMatch(targetPath, patterns = []) {
571
+ if (typeof targetPath !== 'string' || !targetPath.trim()) return false
572
+ let target
573
+ try {
574
+ target = slashedPath(resolve(expandTildePath(targetPath)))
575
+ } catch {
576
+ return false
577
+ }
578
+ for (const raw of patterns ?? []) {
579
+ const text = String(raw ?? '').trim()
580
+ if (!text) continue
581
+ let pattern
582
+ try {
583
+ pattern = slashedPath(resolve(expandTildePath(text)))
584
+ } catch {
585
+ continue
586
+ }
587
+ if (target === pattern) return true
588
+ if (pattern.endsWith('/**') && target === pattern.slice(0, -3)) return true
589
+ const regex = pattern
590
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
591
+ .replace(/\*\*/g, '\u0000')
592
+ .replace(/\*/g, '[^/]*')
593
+ .replace(/\?/g, '[^/]')
594
+ .replace(/\u0000\//g, '(?:.*/)?')
595
+ .replace(/\u0000/g, '.*')
596
+ try {
597
+ if (new RegExp(`^${regex}$`).test(target)) return true
598
+ } catch {
599
+ // an unusable pattern never matches
600
+ }
601
+ }
602
+ return false
603
+ }
604
+
605
+ /** Directory + `/**` so `pathGlobMatch` covers everything inside it. */
606
+ function dirGlob(directory) {
607
+ const clean = String(directory ?? '').replace(/[\\/]+$/, '')
608
+ return clean ? `${clean}/**` : clean
609
+ }
610
+
611
+ /**
612
+ * Directories outside the workspace that tools may write without asking: DSH's own
613
+ * home (configuration, credentials, plugin data), caches and the OS temp directory.
614
+ * Everything else outside the workspace is a long-term destination (v0.7).
615
+ */
616
+ export function defaultOutsideAllow(dshHome) {
617
+ const home = homedir()
618
+ const directories = [
619
+ join(home, '.dsh'),
620
+ join(home, '.cache'),
621
+ join(home, '.npm'),
622
+ join(home, '.config'),
623
+ join(home, '.local', 'share'),
624
+ join(home, '.flova'),
625
+ tmpdir(),
626
+ ]
627
+ if (typeof dshHome === 'string' && dshHome.trim()) directories.push(dshHome)
628
+ if (!IS_WINDOWS) directories.push('/tmp', '/var/tmp', '/dev/shm', '/run/user', '/data/local/tmp', '/storage/emulated/0/Android/data')
629
+ return directories.filter(Boolean).map(dirGlob)
630
+ }
631
+
632
+ /**
633
+ * Classify one write target for the long-term guard.
634
+ *
635
+ * @returns {{kind:'allowed'|'inside-longterm'|'outside'|'skip', abs?:string, reason?:string, scratch?:boolean}}
636
+ * `inside-longterm` = inside the workspace but not under `_tmp`/an approved prefix;
637
+ * `outside` = outside the workspace and not in `outsideAllow`.
638
+ */
639
+ export function classifyWriteTarget(targetPath, cwd, options = {}) {
640
+ const {
641
+ rootDirName = DEFAULT_ROOT,
642
+ allowRootPatterns = DEFAULT_ALLOW_ROOT_PATTERNS,
643
+ allowRootFiles = DEFAULT_ALLOW_ROOT_FILES,
644
+ approvedPrefixes = [],
645
+ outsideAllow = [],
646
+ requireApprovalOutsideTmp = true,
647
+ guardOutsideWorkspace = 'deny',
648
+ baseDir: baseDirOption,
649
+ } = options
650
+ if (!requireApprovalOutsideTmp) return { kind: 'allowed' }
651
+ if (typeof targetPath !== 'string' || !targetPath.trim()) return { kind: 'skip' }
652
+ const base = typeof cwd === 'string' && cwd.trim() ? resolve(cwd) : undefined
653
+ const resolveBase = typeof baseDirOption === 'string' && baseDirOption.trim() ? resolve(baseDirOption) : base
654
+ if (!base && !resolveBase) return { kind: 'skip' }
655
+ let abs
656
+ try {
657
+ const expanded = expandTildePath(targetPath)
658
+ abs = isAbsolute(expanded) ? resolve(expanded) : resolve(resolveBase ?? base, expanded)
659
+ } catch {
660
+ return { kind: 'skip' }
661
+ }
662
+ if (isDevicePath(abs)) return { kind: 'allowed', abs }
663
+ // v0.7 (review M8): a `_tmp` segment only counts as scratch inside the workspace or
664
+ // under the OS temp directory — `Desktop/_tmp/x.md` is still a long-term write.
665
+ if (isScratchPath(abs, rootDirName) && ((base && pathInside(base, abs)) || isSystemTempPath(abs))) {
666
+ return { kind: 'allowed', abs, scratch: true }
667
+ }
668
+ if (base && pathInside(base, abs)) {
669
+ const reason = longtermGuardReason(abs, base, {
670
+ rootDirName,
671
+ allowRootPatterns,
672
+ allowRootFiles,
673
+ approvedPrefixes,
674
+ requireApprovalOutsideTmp,
675
+ })
676
+ return reason ? { kind: 'inside-longterm', abs, reason } : { kind: 'allowed', abs }
677
+ }
678
+ if (approvedPrefixes.some((prefix) => pathInside(prefix, abs))) return { kind: 'allowed', abs }
679
+ if (pathGlobMatch(abs, outsideAllow)) return { kind: 'allowed', abs }
680
+ if (guardOutsideWorkspace === 'off') return { kind: 'allowed', abs }
681
+ return { kind: 'outside', abs }
682
+ }
683
+
684
+ /** Denial reason for a long-term destination outside the workspace. */
685
+ export function outsideWriteDenialReason(abs, options = {}) {
686
+ const { rootDirName = DEFAULT_ROOT, action = '写入' } = options
687
+ return (
688
+ `「${basename(abs)}」在工作区之外(${abs}),属于长期保存位置:${action}前必须先征求用户意见——` +
689
+ `用 ask_user_question 问用户;用户同意后用 longterm_approve 登记该目录再${action};` +
690
+ `用户不同意或属于临时产物 → 用 task_tmpdir 写到 ${rootDirName}/<会话标题>/。`
691
+ )
692
+ }
693
+
694
+ /** Argument names that name a write destination strongly (bare file names are allowed). */
695
+ const STRONG_TARGET_KEYS = new Set([
696
+ 'target',
697
+ 'targets',
698
+ 'target_path',
699
+ 'destination',
700
+ 'dest',
701
+ 'dst',
702
+ 'dest_path',
703
+ 'to',
704
+ 'output',
705
+ 'output_path',
706
+ 'output_dir',
707
+ 'out',
708
+ 'out_path',
709
+ 'save_path',
710
+ 'filename',
711
+ ])
712
+ /** "Looks like a file name" hint used only for strongly-named destination arguments. */
713
+ const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9]{1,8}$/
714
+
715
+ /**
716
+ * True when a string value looks like a filesystem path. Enum-like values
717
+ * (`this_session`, `@e3`, `#submit`, npm package ids, URLs) are rejected on purpose
718
+ * so business arguments are not mistaken for write targets (v0.7 review M1/S2/S3).
719
+ */
720
+ export function looksLikePathValue(value) {
721
+ if (typeof value !== 'string') return false
722
+ const text = value.trim()
723
+ if (!text || text.length > 512) return false
724
+ if (/[\r\n]/.test(text)) return false
725
+ URL_PATTERN.lastIndex = 0
726
+ if (URL_PATTERN.test(text)) return false
727
+ if (/^[@#$]/.test(text)) return false
728
+ if (/^@[\w.-]+\//.test(text)) return false
729
+ if (/^[A-Za-z]:/.test(text)) return true
730
+ if (/^~[/\\]/.test(text)) return true
731
+ if (/^\.{1,2}[/\\]/.test(text)) return true
732
+ if (/[\\/]/.test(text)) return true
733
+ return false
734
+ }
735
+
736
+ /**
737
+ * Top-level path targets of a tool call.
738
+ *
739
+ * v0.7 (review M1): only top-level arguments are inspected — nested business objects
740
+ * (`expect[].target`, `args.files`, …) are not filesystem targets — and arguments
741
+ * declared as `enum` in the tool schema are skipped.
742
+ */
743
+ export function collectPathTargets(args, options = {}) {
744
+ if (!args || typeof args !== 'object') return []
745
+ const { schema } = options
746
+ const enumKeys = new Set()
747
+ const properties = schema?.parameters?.properties
748
+ if (properties && typeof properties === 'object') {
749
+ for (const [key, definition] of Object.entries(properties)) {
750
+ if (definition && typeof definition === 'object' && Array.isArray(definition.enum)) {
751
+ enumKeys.add(key.toLowerCase())
752
+ }
753
+ }
754
+ }
755
+ const out = []
756
+ const push = (key, value) => {
757
+ if (typeof value !== 'string' || !value.trim()) return
758
+ const text = value.trim()
759
+ if (looksLikePathValue(text)) out.push(text)
760
+ else if (STRONG_TARGET_KEYS.has(key.toLowerCase()) && FILE_EXTENSION_PATTERN.test(text)) out.push(text)
761
+ }
762
+ for (const [key, value] of Object.entries(args)) {
763
+ if (!PATH_ARG_PATTERN.test(key)) continue
764
+ if (enumKeys.has(key.toLowerCase())) continue
765
+ if (typeof value === 'string') push(key, value)
766
+ else if (Array.isArray(value)) {
767
+ for (const item of value) {
768
+ if (typeof item === 'string') push(key, item)
769
+ else if (item && typeof item === 'object' && typeof item.path === 'string') push(key, item.path)
770
+ }
771
+ }
772
+ }
773
+ return out
774
+ }
775
+
776
+ /**
777
+ * Best-effort static guard for code-execution tools (`python`, `node`, …).
778
+ *
779
+ * The tool runs arbitrary code, so this cannot be complete: it pairs write signals
780
+ * (`open(...,'w')`, `shutil.copy`, `Path.write_text`, `fs.writeFileSync`, …) with
781
+ * path literals appearing in the same statement and classifies those literals.
782
+ * Dynamically built paths are intentionally out of scope (documented boundary).
783
+ */
784
+ export function codeToolGuardReason(code, cwd, options = {}) {
785
+ if (typeof code !== 'string' || !code.trim()) return undefined
786
+ const rootDirName = options.rootDirName ?? DEFAULT_ROOT
787
+ const signals = []
788
+ CODE_WRITE_SIGNAL.lastIndex = 0
789
+ let match
790
+ while ((match = CODE_WRITE_SIGNAL.exec(code)) !== null) signals.push(match.index)
791
+ if (signals.length === 0) return undefined
792
+ const literals = []
793
+ CODE_PATH_LITERAL.lastIndex = 0
794
+ while ((match = CODE_PATH_LITERAL.exec(code)) !== null) {
795
+ if (match[2]) literals.push({ index: match.index, literal: match[2] })
796
+ }
797
+ if (literals.length === 0) return undefined
798
+ // O(S×L) → linear: signals are already ascending, so a single cursor finds the
799
+ // nearest signal at or before `literal index + window` (v0.7 review A11).
800
+ let cursor = 0
801
+ let nearest = Number.NEGATIVE_INFINITY
802
+ for (const entry of literals) {
803
+ while (cursor < signals.length && signals[cursor] <= entry.index + CODE_SIGNAL_WINDOW) {
804
+ nearest = signals[cursor]
805
+ cursor += 1
806
+ }
807
+ if (!Number.isFinite(nearest) || entry.index - nearest > CODE_SIGNAL_WINDOW) continue
808
+ const verdict = classifyWriteTarget(entry.literal, cwd, options)
809
+ if (typeof options.onTarget === 'function' && verdict?.abs) {
810
+ try {
811
+ options.onTarget(verdict.abs)
812
+ } catch {
813
+ // a reporting callback never changes the verdict
814
+ }
815
+ }
816
+ if (verdict.kind === 'outside') {
817
+ if (options.guardOutsideWorkspace === 'warn') {
818
+ console.info(`[session-task-tmpdir] code guard (warn): ${verdict.abs}`)
819
+ continue
820
+ }
821
+ return `代码执行工具被拦截:${outsideWriteDenialReason(verdict.abs, { rootDirName, action: '写入' })}`
822
+ }
823
+ if (verdict.kind === 'inside-longterm' && !options.skipInside) {
824
+ return `代码执行工具被拦截:${verdict.reason}(代码里的写入目标:${verdict.abs})`
825
+ }
826
+ }
827
+ return undefined
828
+ }
829
+
830
+ /** Argument names of a delivery tool that name the copy destination. */
831
+ const COPY_TARGET_KEYS = new Set([
832
+ 'target',
833
+ 'targets',
834
+ 'target_path',
835
+ 'destination',
836
+ 'dest',
837
+ 'dst',
838
+ 'dest_path',
839
+ 'to',
840
+ 'output',
841
+ 'output_path',
842
+ 'output_dir',
843
+ 'out',
844
+ 'out_path',
845
+ 'save_path',
846
+ 'dir',
847
+ 'directory',
848
+ 'filename',
849
+ ])
850
+
851
+ /** First path argument of a write/edit-style tool call. */
852
+ export function firstWriteTarget(args) {
853
+ if (!args || typeof args !== 'object') return undefined
854
+ const candidates = [args.file_path, args.file_paths, args.path, args.file, args.files]
855
+ for (const candidate of candidates) {
856
+ if (typeof candidate === 'string' && candidate.trim()) return candidate.trim()
857
+ if (Array.isArray(candidate)) {
858
+ for (const item of candidate) {
859
+ if (typeof item === 'string' && item.trim()) return item.trim()
860
+ if (item && typeof item === 'object' && typeof item.path === 'string' && item.path.trim()) {
861
+ return item.path.trim()
862
+ }
863
+ }
864
+ }
865
+ }
866
+ return undefined
867
+ }
868
+
869
+ /**
870
+ * Copy destinations of a delivery tool (`publish`). Source/read arguments are
871
+ * skipped on purpose: copying *from* a long-term folder is harmless.
872
+ */
873
+ export function publishWriteTargets(args) {
874
+ if (!args || typeof args !== 'object') return []
875
+ const out = []
876
+ const push = (value) => {
877
+ if (typeof value === 'string' && value.trim()) out.push(value.trim())
878
+ }
879
+ for (const [key, value] of Object.entries(args)) {
880
+ const lower = key.toLowerCase()
881
+ if (SOURCE_PATH_ARG_PATTERN.test(lower)) continue
882
+ if (!COPY_TARGET_KEYS.has(lower)) continue
883
+ if (typeof value === 'string') push(value)
884
+ else if (Array.isArray(value)) value.forEach(push)
885
+ else if (value && typeof value === 'object') {
886
+ for (const nested of Object.values(value)) push(nested)
887
+ }
888
+ }
889
+ const files = Array.isArray(args.files) ? args.files : []
890
+ for (const file of files) {
891
+ if (typeof file === 'string') push(file)
892
+ else if (file && typeof file === 'object') push(file.path ?? file.target)
893
+ }
894
+ return [...new Set(out)]
895
+ }
896
+
897
+ /** Code text of a code-execution tool call (argument name differs per Host). */
898
+ export function codeTextOf(args) {
899
+ if (!args || typeof args !== 'object') return undefined
900
+ for (const key of ['code', 'script', 'source', 'python', 'ruby', 'js', 'command']) {
901
+ if (typeof args[key] === 'string' && args[key].trim()) return args[key]
902
+ }
903
+ return undefined
904
+ }
905
+
906
+ /**
907
+ * Decide which guard channel a tool call belongs to.
908
+ *
909
+ * Known write tools keep their dedicated path arguments; `publish` uses its copy
910
+ * target; code tools are scanned statically; anything else that declares a path
911
+ * argument and looks write-capable is inspected as `unknown` (only the two
912
+ * high-risk destinations are denied for that channel).
913
+ */
914
+ export function toolWritePlan(toolName, args, options = {}) {
915
+ const name = String(toolName ?? '').trim()
916
+ if (!name || !args || typeof args !== 'object') return { channel: 'skip' }
917
+ const lower = name.toLowerCase()
918
+ const {
919
+ writeToolNames = [...WRITE_TOOL_NAMES],
920
+ publishToolNames = [...PUBLISH_TOOL_NAMES],
921
+ codeToolNames = [...CODE_TOOL_NAMES],
922
+ shellToolNames = [...SHELL_TOOL_NAMES],
923
+ guardCodeTools = true,
924
+ guardUnknownTools = true,
925
+ guardPublish = true,
926
+ schema,
927
+ } = options
928
+ // v0.7 (review S1): the plugin's own tools must always pass their own guard —
929
+ // `longterm_approve` is the escape hatch the denial messages point at.
930
+ if (SELF_TOOL_NAMES.has(lower)) return { channel: 'skip' }
931
+ const matches = (list) => (Array.isArray(list) ? list.some((entry) => String(entry).toLowerCase() === lower) : false)
932
+ if (matches(codeToolNames)) return guardCodeTools ? { channel: 'code' } : { channel: 'skip' }
933
+ if (matches(shellToolNames)) return { channel: 'shell' }
934
+ if (matches(publishToolNames)) {
935
+ // `present` only declares files that already exist; it copies nothing.
936
+ if (lower === 'present') return { channel: 'skip' }
937
+ return guardPublish ? { channel: 'publish' } : { channel: 'skip' }
938
+ }
939
+ if (matches(writeToolNames)) return { channel: 'write' }
940
+ if (!guardUnknownTools) return { channel: 'skip' }
941
+ // v0.7 (review S4): a read-only tool stays read-only even when its description
942
+ // mentions writing in a negation ("do not install libraries or create thumbnails").
943
+ if (READ_ONLY_TOOL_PATTERN.test(lower)) return { channel: 'skip' }
944
+ const description = typeof schema?.description === 'string' ? schema.description : ''
945
+ if (!WRITE_HINT_PATTERN.test(`${lower} ${description}`)) return { channel: 'skip' }
946
+ // v0.7 (review M1/S2/S3): only top-level arguments whose values actually look like
947
+ // paths count; enum-like values (`this_session`, `@e3`, `#submit`, package ids) do not.
948
+ const targets = collectPathTargets(args, { schema })
949
+ if (targets.length === 0) return { channel: 'skip' }
950
+ const parameters = schema?.parameters && typeof schema.parameters === 'object' ? schema.parameters : undefined
951
+ const pathParams =
952
+ parameters?.properties && typeof parameters.properties === 'object'
953
+ ? Object.keys(parameters.properties).filter((key) => PATH_ARG_PATTERN.test(key))
954
+ : []
955
+ return { channel: 'unknown', pathParams }
956
+ }
957
+
958
+ async function readMarker(dir) {
959
+ try {
960
+ return JSON.parse(await readFile(join(dir, MARKER_FILE), 'utf8'))
961
+ } catch {
962
+ return undefined
963
+ }
964
+ }
965
+
966
+ async function writeMarker(dir, sessionId, title, orphanedAt) {
967
+ const payload = { sessionId: String(sessionId), title: title ?? '', updatedAt: Date.now() }
968
+ if (Number.isFinite(orphanedAt) && orphanedAt > 0) payload.orphanedAt = orphanedAt
969
+ try {
970
+ await writeFile(join(dir, MARKER_FILE), JSON.stringify(payload, null, 2), 'utf8')
971
+ } catch {
972
+ // marker is best-effort; the folder still works without it
973
+ }
974
+ }
975
+
976
+ /**
977
+ * v0.8 (claim-on-write): the `<rootDirName>/<dir>/` folders a set of write targets
978
+ * lands in. Used by the guard to stamp a marker on folders the model created with a
979
+ * plain `write`/shell command instead of `task_tmpdir`, so they join the same 7-day
980
+ * orphan cleanup chain. Pure and exported for tests.
981
+ *
982
+ * @param {Iterable<string>} targets raw (possibly relative) write targets
983
+ * @param {string} cwd session working directory
984
+ * @param {string} [rootDirName] temp root name (default `_tmp`)
985
+ * @returns {string[]} absolute directories directly under `<cwd>/<rootDirName>/`
986
+ */
987
+ export function tmpClaimDirsForTargets(targets, cwd, rootDirName = DEFAULT_ROOT, { allowDirItself = false } = {}) {
988
+ const result = new Set()
989
+ if (typeof cwd !== 'string' || !cwd.trim()) return []
990
+ const root = join(resolve(cwd), rootDirName)
991
+ for (const raw of targets ?? []) {
992
+ if (typeof raw !== 'string' || !raw.trim()) continue
993
+ let abs
994
+ try {
995
+ const expanded = expandTildePath(raw.trim())
996
+ abs = isAbsolute(expanded) ? resolve(expanded) : resolve(cwd, expanded)
997
+ } catch {
998
+ continue
999
+ }
1000
+ if (isDevicePath(abs)) continue
1001
+ if (!pathInside(root, abs)) continue
1002
+ const child = firstSegmentUnder(root, abs)
1003
+ if (!child) continue
1004
+ const dir = join(root, child)
1005
+ if (normalizeForCompare(dir) !== normalizeForCompare(abs)) {
1006
+ // target lives inside `<root>/<child>/…`
1007
+ result.add(dir)
1008
+ continue
1009
+ }
1010
+ // target is exactly `<root>/<child>`: the write tools target files, so they never
1011
+ // claim the folder itself; a shell command that creates directories (`mkdir`,
1012
+ // `New-Item -ItemType Directory`, `git clone`, …) may, because the target is a
1013
+ // folder and not a file. A command that writes a file (`> _tmp/out`) never creates
1014
+ // the folder, so it must not be claimed here either.
1015
+ if (!allowDirItself) continue
1016
+ try {
1017
+ if (statSync(abs).isFile()) continue
1018
+ } catch {
1019
+ // not created yet — the directory verb tells us the command will create it
1020
+ }
1021
+ if (FILE_EXTENSION_PATTERN.test(child)) continue
1022
+ result.add(dir)
1023
+ }
1024
+ return [...result]
1025
+ }
1026
+
1027
+ /**
1028
+ * v0.8: relative `<rootDirName>/<dir>` mentions a shell command may contain. The shell
1029
+ * guard only scans absolute paths, so `New-Item _tmp/foo` would otherwise stay unowned.
1030
+ * Mentioned paths are treated as relative to the session working directory. Exported
1031
+ * for tests.
1032
+ */
1033
+ export function relativeTmpTargets(command) {
1034
+ const out = []
1035
+ if (typeof command !== 'string' || !command.trim()) return out
1036
+ const text = command.replace(URL_PATTERN, ' ')
1037
+ for (const match of text.matchAll(TMP_RELATIVE_PATTERN)) {
1038
+ if (match[1]) out.push(match[1])
1039
+ }
1040
+ return out
1041
+ }
1042
+
1043
+ /**
1044
+ * v0.8: rough "this shell command creates a directory" test. Only such commands may
1045
+ * claim a target that is exactly `<root>/<dir>` (no deeper path component) before the
1046
+ * folder exists — a file-writing command (`> _tmp/out`, `Set-Content _tmp/notes`) must
1047
+ * never be turned into a folder. Exported for tests.
1048
+ */
1049
+ export function commandCreatesDirectory(command) {
1050
+ if (typeof command !== 'string' || !command.trim()) return false
1051
+ return CREATE_DIR_HINT_PATTERN.test(command)
1052
+ }
1053
+
1054
+ /**
1055
+ * v0.8: stamp `.dsh-task.json` on unmarked temp folders, synchronously. The guard runs
1056
+ * before the tool executes, so the folder may not exist yet; creating it is harmless
1057
+ * because the write that triggered the claim is about to land inside it anyway.
1058
+ * Existing markers are never overwritten (a folder owned by another session stays its).
1059
+ */
1060
+ export function claimTmpDirsSync(dirs, sessionId, title, { log = () => {} } = {}) {
1061
+ const claimed = []
1062
+ if (!sessionId) return claimed
1063
+ for (const dir of dirs ?? []) {
1064
+ if (typeof dir !== 'string' || !dir.trim()) continue
1065
+ try {
1066
+ if (existsSync(join(dir, MARKER_FILE))) continue
1067
+ mkdirSync(dir, { recursive: true })
1068
+ writeFileSync(
1069
+ join(dir, MARKER_FILE),
1070
+ JSON.stringify({ sessionId: String(sessionId), title: title ?? '', updatedAt: Date.now() }, null, 2),
1071
+ 'utf8',
1072
+ )
1073
+ claimed.push(dir)
1074
+ log(dir)
1075
+ } catch {
1076
+ // best-effort: a failed claim never blocks the write
1077
+ }
1078
+ }
1079
+ return claimed
1080
+ }
1081
+
1082
+ /**
1083
+ * Delete marker-owned task folders whose owning session has been gone for `orphanDays`.
1084
+ *
1085
+ * @param {object} options
1086
+ * @param {Iterable<string>} options.roots workspace directories to scan
1087
+ * @param {string} [options.rootDirName] temp root name (default `_tmp`)
1088
+ * @param {number} options.orphanDays days after session deletion before removal (0 disables)
1089
+ * @param {boolean} [options.dryRun] report only, write/delete nothing
1090
+ * @param {Iterable<string>} [options.liveSessionIds] currently live sessions (never removed)
1091
+ * @param {Iterable<string>} [options.existingSessionIds] persisted sessions (never removed)
1092
+ * @param {number} [options.now] timestamp override (tests)
1093
+ * @param {(message: string) => void} [options.log] progress logger
1094
+ * @returns {Promise<object>} report
1095
+ */
1096
+ export async function cleanupOrphanedTempDirs({
1097
+ roots,
1098
+ rootDirName = DEFAULT_ROOT,
1099
+ orphanDays,
1100
+ dryRun = false,
1101
+ liveSessionIds = [],
1102
+ existingSessionIds = [],
1103
+ now = Date.now(),
1104
+ log = () => {},
1105
+ }) {
1106
+ const report = {
1107
+ dryRun,
1108
+ cutoff: now - orphanDays * DAY_MS,
1109
+ roots: [],
1110
+ markedOrphaned: [],
1111
+ deleted: [],
1112
+ kept: { live: 0, alive: 0, unmarked: 0, waiting: 0, error: 0 },
1113
+ }
1114
+ if (!(orphanDays > 0)) return report
1115
+ const live = new Set([...liveSessionIds].map((id) => String(id)))
1116
+ const known = new Set([...existingSessionIds].map((id) => String(id)))
1117
+ for (const id of live) known.add(id)
1118
+ const uniqueRoots = new Set([...roots].filter((root) => typeof root === 'string' && root.trim() !== ''))
1119
+
1120
+ for (const root of uniqueRoots) {
1121
+ const tmpRoot = join(root, rootDirName)
1122
+ let entries
1123
+ try {
1124
+ entries = await readdir(tmpRoot, { withFileTypes: true })
1125
+ } catch {
1126
+ continue
1127
+ }
1128
+ report.roots.push(tmpRoot)
1129
+ for (const entry of entries) {
1130
+ if (!entry.isDirectory() || entry.isSymbolicLink()) continue
1131
+ const dir = join(tmpRoot, entry.name)
1132
+ try {
1133
+ const marker = await readMarker(dir)
1134
+ if (!marker) {
1135
+ report.kept.unmarked += 1
1136
+ continue
1137
+ }
1138
+ const sessionId = String(marker.sessionId ?? '')
1139
+ if (!sessionId) {
1140
+ report.kept.unmarked += 1
1141
+ continue
1142
+ }
1143
+ if (live.has(sessionId)) {
1144
+ report.kept.live += 1
1145
+ continue
1146
+ }
1147
+ if (known.has(sessionId)) {
1148
+ report.kept.alive += 1
1149
+ if (Number(marker.orphanedAt) > 0 && !dryRun) await writeMarker(dir, sessionId, marker.title, undefined)
1150
+ continue
1151
+ }
1152
+ // Owning session no longer exists.
1153
+ const orphanedAt = Number(marker.orphanedAt) || 0
1154
+ if (orphanedAt <= 0) {
1155
+ report.markedOrphaned.push(dir)
1156
+ if (dryRun) {
1157
+ report.kept.waiting += 1
1158
+ log(`[dry-run] would mark orphaned ${dir}`)
1159
+ } else {
1160
+ await writeMarker(dir, sessionId, marker.title, now)
1161
+ log(`marked orphaned ${dir}`)
1162
+ }
1163
+ continue
1164
+ }
1165
+ if (now - orphanedAt < orphanDays * DAY_MS) {
1166
+ report.kept.waiting += 1
1167
+ continue
1168
+ }
1169
+ if (dryRun) {
1170
+ report.deleted.push({ path: dir, dryRun: true })
1171
+ log(`[dry-run] would delete ${dir}`)
1172
+ continue
1173
+ }
1174
+ await rm(dir, { recursive: true, force: true })
1175
+ report.deleted.push({ path: dir })
1176
+ log(`deleted ${dir}`)
1177
+ } catch {
1178
+ report.kept.error += 1
1179
+ }
1180
+ }
1181
+ }
1182
+ return report
1183
+ }
1184
+
1185
+ /** 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() : ''
1188
+ return fromEnv || join(homedir(), '.dsh')
1189
+ }
1190
+
1191
+ /** Best-effort fallback: collect session ids from the persisted session tree. */
1192
+ async function scanPersistedSessionIds() {
1193
+ const ids = new Set()
1194
+ const home = resolveDshHome()
1195
+ const roots = [join(home, 'sessions'), join(home, '_archived-sessions')]
1196
+ const idPattern = /^(?:session-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
1197
+ for (const root of roots) {
1198
+ let workspaces
1199
+ try {
1200
+ workspaces = await readdir(root, { withFileTypes: true })
1201
+ } catch {
1202
+ continue
1203
+ }
1204
+ for (const workspace of workspaces) {
1205
+ if (!workspace.isDirectory()) continue
1206
+ const workspaceDir = join(root, workspace.name)
1207
+ // Session directories live one level below; also cover a flat layout.
1208
+ if (idPattern.test(workspace.name)) {
1209
+ ids.add(workspace.name.replace(/^session-/, ''))
1210
+ continue
1211
+ }
1212
+ let sessions
1213
+ try {
1214
+ sessions = await readdir(workspaceDir, { withFileTypes: true })
1215
+ } catch {
1216
+ continue
1217
+ }
1218
+ for (const session of sessions) {
1219
+ if (!session.isDirectory()) continue
1220
+ if (idPattern.test(session.name)) ids.add(session.name.replace(/^session-/, ''))
1221
+ }
1222
+ }
1223
+ }
1224
+ return ids
1225
+ }
1226
+
1227
+ /**
1228
+ * Collect `sha256:` attachment ids from an arbitrary session-event payload.
1229
+ *
1230
+ * Attachment references are stored as `{ attachmentId: 'sha256:<hex>', ... }` inside
1231
+ * `image` / `file` content blocks; walking the parsed event keeps this independent of
1232
+ * where a block lives (user message, tool result, spliced inbox, …).
1233
+ *
1234
+ * @param {unknown} value parsed session event (or any nested JSON value)
1235
+ * @param {Set<string>} [out] accumulator of hex hashes
1236
+ * @param {number} [depth] recursion guard
1237
+ * @returns {Set<string>}
1238
+ */
1239
+ export function collectAttachmentIds(value, out = new Set(), depth = 0) {
1240
+ if (!value || depth > 24) return out
1241
+ if (Array.isArray(value)) {
1242
+ for (const item of value) collectAttachmentIds(item, out, depth + 1)
1243
+ return out
1244
+ }
1245
+ if (typeof value !== 'object') return out
1246
+ for (const [key, item] of Object.entries(value)) {
1247
+ if (key === 'attachmentId' && typeof item === 'string') {
1248
+ const match = ATTACHMENT_ID_PATTERN.exec(item)
1249
+ if (match) out.add(match[1].toLowerCase())
1250
+ continue
1251
+ }
1252
+ collectAttachmentIds(item, out, depth + 1)
1253
+ }
1254
+ return out
1255
+ }
1256
+
1257
+ /** Read the attachment ledger; a missing or unreadable file yields an empty ledger. */
1258
+ async function readAttachmentLedger(path) {
1259
+ try {
1260
+ const parsed = JSON.parse(await readFile(path, 'utf8'))
1261
+ if (parsed && typeof parsed === 'object' && parsed.sessions && typeof parsed.sessions === 'object') {
1262
+ return {
1263
+ version: ATTACHMENT_LEDGER_VERSION,
1264
+ sessions: parsed.sessions,
1265
+ lastSweepAt: Number(parsed.lastSweepAt) || 0,
1266
+ }
1267
+ }
1268
+ } catch {
1269
+ // missing or corrupt ledger: start from scratch
1270
+ }
1271
+ return { version: ATTACHMENT_LEDGER_VERSION, sessions: {}, lastSweepAt: 0 }
1272
+ }
1273
+
1274
+ /** Write the ledger atomically (temp file + rename), best-effort. */
1275
+ async function writeAttachmentLedger(path, ledger) {
1276
+ const temp = `${path}.tmp`
1277
+ try {
1278
+ await mkdir(dirname(path), { recursive: true })
1279
+ await writeFile(temp, JSON.stringify(ledger), 'utf8')
1280
+ await rename(temp, path)
1281
+ } catch {
1282
+ // ledger persistence is an optimization; a failed write only costs a rescan
1283
+ }
1284
+ }
1285
+
1286
+ /**
1287
+ * List every stored attachment blob.
1288
+ * @param {string} attachmentsRoot attachment service root (default `<DSH_HOME>/attachments`)
1289
+ * @returns {Promise<Array<{ hash: string, path: string, bytes: number, mtime: number }>>}
1290
+ */
1291
+ async function listAttachmentBlobs(attachmentsRoot) {
1292
+ const objectsDir = join(attachmentsRoot, 'v1', 'objects')
1293
+ /** @type {Array<{ hash: string, path: string, bytes: number, mtime: number }>} */
1294
+ const blobs = []
1295
+ let buckets
1296
+ try {
1297
+ buckets = await readdir(objectsDir, { withFileTypes: true })
1298
+ } catch {
1299
+ return blobs
1300
+ }
1301
+ for (const bucket of buckets) {
1302
+ if (!bucket.isDirectory()) continue
1303
+ const bucketDir = join(objectsDir, bucket.name)
1304
+ let files
1305
+ try {
1306
+ files = await readdir(bucketDir, { withFileTypes: true })
1307
+ } catch {
1308
+ continue
1309
+ }
1310
+ for (const file of files) {
1311
+ if (!file.isFile() || !/^[0-9a-f]{64}$/i.test(file.name)) continue
1312
+ const full = join(bucketDir, file.name)
1313
+ try {
1314
+ const info = await stat(full)
1315
+ blobs.push({ hash: file.name.toLowerCase(), path: full, bytes: info.size, mtime: info.mtimeMs })
1316
+ } catch {
1317
+ /* raced with a delete */
1318
+ }
1319
+ }
1320
+ }
1321
+ return blobs
1322
+ }
1323
+
1324
+ export function apply(ctx, config) {
1325
+ const {
1326
+ rootDirName,
1327
+ includeSubagents,
1328
+ maxNameLength,
1329
+ orphanCleanupDays,
1330
+ cleanupIntervalHours,
1331
+ cleanupDryRun,
1332
+ guardWorkspaceRoot,
1333
+ requireApprovalOutsideTmp,
1334
+ allowRootPatterns,
1335
+ allowRootFiles,
1336
+ commandGuard,
1337
+ guardOutsideWorkspace,
1338
+ publishGuard,
1339
+ guardCodeTools,
1340
+ guardUnknownTools,
1341
+ writeToolNames,
1342
+ publishToolNames,
1343
+ codeToolNames,
1344
+ shellToolNames,
1345
+ outsideAllow: extraOutsideAllow,
1346
+ publishBaseDir,
1347
+ attachmentCleanup,
1348
+ attachmentCleanupDays,
1349
+ attachmentSweepOrphans,
1350
+ attachmentsDir,
1351
+ } = readConfig(config)
1352
+ /** Directories outside the workspace that never need approval (DSH home, caches, temp). */
1353
+ const outsideAllow = [...defaultOutsideAllow(resolveDshHome()), ...extraOutsideAllow]
1354
+ const queues = new Map()
1355
+ /** sessionId → approved long-term prefixes ({ prefix, reason, basis, approvedAt }[]). */
1356
+ const approvals = new Map()
1357
+ let sessionPersistence
1358
+ let workspaceRegistry
1359
+ try {
1360
+ ctx.inject(['sessionPersistence'], (scoped) => {
1361
+ sessionPersistence = scoped.sessionPersistence
1362
+ })
1363
+ } catch {
1364
+ // fallback: the persisted session tree is scanned directly
1365
+ }
1366
+ try {
1367
+ ctx.inject(['workspaceRegistry'], (scoped) => {
1368
+ workspaceRegistry = scoped.workspaceRegistry
1369
+ })
1370
+ } catch {
1371
+ // workspaceRegistry is optional; live sessions and the default directory still cover roots
1372
+ }
1373
+
1374
+ const cwdOf = (session) => {
1375
+ try {
1376
+ const dir = ctx.workingDirectory.get(session)
1377
+ if (typeof dir === 'string' && dir) return dir
1378
+ } catch {
1379
+ // fall through to the header value
1380
+ }
1381
+ const headerCwd = session?.header?.cwd
1382
+ return typeof headerCwd === 'string' && headerCwd ? headerCwd : undefined
1383
+ }
1384
+
1385
+ const titleOf = (session) => {
1386
+ try {
1387
+ const snapshot = ctx.sessionTitle.get(session)
1388
+ if (snapshot?.title) return snapshot.title
1389
+ } catch {
1390
+ // title provider may be absent or the session may be detached
1391
+ }
1392
+ return undefined
1393
+ }
1394
+
1395
+ const isRelevant = (session) => includeSubagents || session?.header?.origin !== 'subagent'
1396
+
1397
+ /**
1398
+ * The root-entry guard only makes sense when the session is working at a workspace
1399
+ * root. A session `cd`-ed into a subfolder (or a subagent started in a plugin dir)
1400
+ * must not have its project files treated as "new workspace-root entries".
1401
+ */
1402
+ function isProtectedRoot(cwd) {
1403
+ let workspaces = []
1404
+ try {
1405
+ workspaces = workspaceRegistry?.list() ?? []
1406
+ } catch {
1407
+ workspaces = []
1408
+ }
1409
+ if (workspaces.length > 0) return workspaces.some((workspace) => samePath(workspace?.path, cwd))
1410
+ // Registry not ready: keep the historical strict behavior, default directory still counts.
1411
+ try {
1412
+ const defaultDir = ctx.workingDirectory.defaultDirectory
1413
+ if (typeof defaultDir === 'string' && defaultDir) return samePath(defaultDir, cwd)
1414
+ } catch {
1415
+ // no default directory
1416
+ }
1417
+ return true
1418
+ }
1419
+
1420
+ const baseDir = (cwd) => join(cwd, rootDirName)
1421
+
1422
+ // ── long-term approvals (per live session, in memory) ──────────────────────
1423
+ const sessionKey = (session) => {
1424
+ try {
1425
+ return session?.id ? String(session.id) : ''
1426
+ } catch {
1427
+ return ''
1428
+ }
1429
+ }
1430
+
1431
+ /**
1432
+ * v0.8 claim-on-write: attribute unmarked `<rootDirName>/<dir>/` folders touched by
1433
+ * this session's writes to the session, so every folder the model creates joins the
1434
+ * 7-day orphan cleanup chain even when it bypassed `task_tmpdir`.
1435
+ */
1436
+ function claimTmpTargets(targets, session, options = {}) {
1437
+ try {
1438
+ const dirs = tmpClaimDirsForTargets(targets, cwdOf(session), rootDirName, options)
1439
+ if (dirs.length === 0) return
1440
+ claimTmpDirsSync(dirs, sessionKey(session), titleOf(session) ?? '', {
1441
+ log: (dir) => console.info(`[session-task-tmpdir] claimed unmarked temp folder: ${dir}`),
1442
+ })
1443
+ } catch {
1444
+ // claiming is best-effort
1445
+ }
1446
+ }
1447
+
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
1465
+ }
1466
+
1467
+ async function isDir(path) {
1468
+ try {
1469
+ return (await stat(path)).isDirectory()
1470
+ } catch {
1471
+ return false
1472
+ }
1473
+ }
1474
+
1475
+ async function findOwnedDir(cwd, sessionId) {
1476
+ const root = baseDir(cwd)
1477
+ let entries
1478
+ try {
1479
+ entries = await readdir(root, { withFileTypes: true })
1480
+ } catch {
1481
+ return undefined
1482
+ }
1483
+ for (const entry of entries) {
1484
+ if (!entry.isDirectory()) continue
1485
+ const dir = join(root, entry.name)
1486
+ const marker = await readMarker(dir)
1487
+ if (marker && String(marker.sessionId) === String(sessionId)) return dir
1488
+ }
1489
+ return undefined
1490
+ }
1491
+
1492
+ /**
1493
+ * Pick a target path for `name`: reuse the folder owned by this session, adopt an
1494
+ * empty unowned folder (removing it first when `removeEmpty` prepares a rename),
1495
+ * otherwise append a numeric suffix.
1496
+ */
1497
+ async function chooseTarget(root, name, sessionId, { removeEmpty = false } = {}) {
1498
+ let target = join(root, name)
1499
+ let n = 2
1500
+ for (;;) {
1501
+ if (!(await isDir(target))) return target
1502
+ const marker = await readMarker(target)
1503
+ if (marker && sessionId !== undefined && String(marker.sessionId) === String(sessionId)) return target
1504
+ const entries = await readdir(target).catch(() => [])
1505
+ if (!marker && entries.length === 0) {
1506
+ if (!removeEmpty) return target
1507
+ await rm(target, { recursive: true, force: true }).catch(() => {})
1508
+ return target
1509
+ }
1510
+ target = join(root, `${name} (${n++})`)
1511
+ }
1512
+ }
1513
+
1514
+ async function createDir(session, sub) {
1515
+ const cwd = cwdOf(session)
1516
+ if (!cwd) throw new Error('session working directory is unavailable')
1517
+ const title = titleOf(session)
1518
+ const name = sanitizeTitle(title, maxNameLength) || `${FALLBACK_PREFIX}${String(session.id).slice(0, 8)}`
1519
+ const root = baseDir(cwd)
1520
+ await mkdir(root, { recursive: true })
1521
+ // Reuse the folder this session already owns (e.g. a `sub` call after the first call)
1522
+ const owned = await findOwnedDir(cwd, session.id)
1523
+ const target = owned ?? (await chooseTarget(root, name, session.id))
1524
+ await mkdir(target, { recursive: true })
1525
+ await writeMarker(target, session.id, title ?? '')
1526
+ const path = sub ? join(target, sanitizeTitle(sub, maxNameLength) || 'sub') : target
1527
+ if (sub) await mkdir(path, { recursive: true })
1528
+ return { path, title: title ?? '' }
1529
+ }
1530
+
1531
+ async function syncDir(session) {
1532
+ const cwd = cwdOf(session)
1533
+ if (!cwd) return
1534
+ const title = titleOf(session)
1535
+ if (!title) return
1536
+ const name = sanitizeTitle(title, maxNameLength)
1537
+ if (!name) return
1538
+ const root = baseDir(cwd)
1539
+ const owned = await findOwnedDir(cwd, session.id)
1540
+ if (!owned) {
1541
+ await createDir(session)
1542
+ return
1543
+ }
1544
+ if (owned === join(root, name)) {
1545
+ await writeMarker(owned, session.id, title)
1546
+ return
1547
+ }
1548
+ const target = await chooseTarget(root, name, session.id, { removeEmpty: true })
1549
+ if (target === owned) return
1550
+ try {
1551
+ await rename(owned, target)
1552
+ } catch (error) {
1553
+ // A locked file can block the rename on Windows; keep the old folder and its marker.
1554
+ console.warn('[session-task-tmpdir] rename failed:', error?.message ?? error)
1555
+ return
1556
+ }
1557
+ await writeMarker(target, session.id, title)
1558
+ }
1559
+
1560
+ function enqueue(session) {
1561
+ const id = String(session.id)
1562
+ const previous = queues.get(id) ?? Promise.resolve()
1563
+ const next = previous
1564
+ .then(() => syncDir(session))
1565
+ .catch((error) => console.warn('[session-task-tmpdir] sync failed:', error?.message ?? error))
1566
+ .finally(() => {
1567
+ if (queues.get(id) === next) queues.delete(id)
1568
+ })
1569
+ queues.set(id, next)
1570
+ }
1571
+
1572
+ // Title change (user rename and automatic title regeneration both append session/title).
1573
+ ctx.effect(() =>
1574
+ ctx.on('session/event', (session, event) => {
1575
+ if (event?.type !== 'session/title') return
1576
+ if (!session || !isRelevant(session)) return
1577
+ enqueue(session)
1578
+ }),
1579
+ )
1580
+
1581
+ // A resumed session may already carry a title; materialize the folder on creation.
1582
+ ctx.effect(() =>
1583
+ ctx.on('session/created', (session) => {
1584
+ if (!session || !isRelevant(session)) return
1585
+ enqueue(session)
1586
+ }),
1587
+ )
1588
+
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
+ )
1596
+
1597
+ // ── orphan cleanup ─────────────────────────────────────────────────────────
1598
+ let cleaning = false
1599
+
1600
+ async function loadPersistenceSnapshots() {
1601
+ if (sessionPersistence && typeof sessionPersistence.list === 'function') {
1602
+ try {
1603
+ return await sessionPersistence.list()
1604
+ } catch {
1605
+ // fall through to the directory scan
1606
+ }
1607
+ }
1608
+ return undefined
1609
+ }
1610
+
1611
+ async function collectPersistedSessionIds() {
1612
+ const snapshots = await loadPersistenceSnapshots()
1613
+ if (snapshots) return snapshots.map((snapshot) => String(snapshot?.header?.id ?? '')).filter(Boolean)
1614
+ return [...(await scanPersistedSessionIds())]
1615
+ }
1616
+
1617
+ // ── attachment cleanup (v0.6) ───────────────────────────────────────────────
1618
+ // The attachment store is content-addressed and never garbage collected by the Host,
1619
+ // so deleting a conversation leaves its blobs behind forever. Every cleanup tick we
1620
+ // record the attachment ids each *stored* session references (ledger), stamp the
1621
+ // moment a session disappears, and only once that stamp is older than
1622
+ // `attachmentCleanupDays` delete the blobs no surviving session references.
1623
+ const attachmentsRoot = attachmentsDir
1624
+ const attachmentLedgerPath = join(resolveDshHome(), 'data', ATTACHMENT_LEDGER_FILE)
1625
+ const attachmentGcLogPath = join(resolveDshHome(), 'data', ATTACHMENT_GC_LOG_FILE)
1626
+
1627
+ /** Read one stored session through the persistence service and collect its attachment ids. */
1628
+ async function readSessionAttachmentIds(sessionId) {
1629
+ if (!sessionPersistence || typeof sessionPersistence.open !== 'function') return undefined
1630
+ let handle
1631
+ try {
1632
+ handle = await sessionPersistence.open(sessionId, 'read')
1633
+ } catch {
1634
+ return undefined
1635
+ }
1636
+ const ids = new Set()
1637
+ try {
1638
+ let offset = 0
1639
+ for (let page = 0; page < ATTACHMENT_READ_PAGE_LIMIT; page += 1) {
1640
+ const result = await handle.read(offset, ATTACHMENT_READ_PAGE_SIZE)
1641
+ const events = Array.isArray(result?.events) ? result.events : []
1642
+ if (events.length === 0) break
1643
+ for (const event of events) collectAttachmentIds(event, ids)
1644
+ const lastSeq = Number(events[events.length - 1]?.seq)
1645
+ if (!Number.isFinite(lastSeq) || lastSeq < offset) break
1646
+ offset = lastSeq + 1
1647
+ if (events.length < ATTACHMENT_READ_PAGE_SIZE) break
1648
+ }
1649
+ } catch {
1650
+ // torn or unreadable tail: keep whatever was collected so far
1651
+ } finally {
1652
+ try {
1653
+ await handle.close()
1654
+ } catch {
1655
+ /* already closed */
1656
+ }
1657
+ }
1658
+ return ids
1659
+ }
1660
+
1661
+ /**
1662
+ * Delete attachment blobs whose owning session has been gone for `attachmentCleanupDays`,
1663
+ * plus (optionally) blobs no stored session references and that are at least that old.
1664
+ */
1665
+ async function runAttachmentCleanup(trigger, { dryRun = cleanupDryRun } = {}) {
1666
+ if (!attachmentCleanup) return { skipped: 'disabled' }
1667
+ const snapshots = await loadPersistenceSnapshots()
1668
+ if (!snapshots) return { skipped: 'sessionPersistence-unavailable' }
1669
+ if (snapshots.length === 0) return { skipped: 'no-stored-sessions' }
1670
+ const now = Date.now()
1671
+ const liveSessionIds = new Set()
1672
+ try {
1673
+ for (const session of ctx.sessions.list()) liveSessionIds.add(String(session.id))
1674
+ } catch {
1675
+ /* sessions unavailable this tick */
1676
+ }
1677
+ const ledger = await readAttachmentLedger(attachmentLedgerPath)
1678
+ const alive = new Set()
1679
+ const referenced = new Set()
1680
+ let rescanned = 0
1681
+ let scannedFailures = 0
1682
+ for (const snapshot of snapshots) {
1683
+ const id = String(snapshot?.header?.id ?? '')
1684
+ if (!id) continue
1685
+ alive.add(id)
1686
+ const revision = String(snapshot?.revision ?? '')
1687
+ const entry = ledger.sessions[id]
1688
+ let hashes
1689
+ if (entry && entry.revision === revision && Array.isArray(entry.hashes)) {
1690
+ hashes = entry.hashes
1691
+ } else {
1692
+ const scanned = await readSessionAttachmentIds(id)
1693
+ if (!scanned) {
1694
+ scannedFailures += 1
1695
+ if (entry && Array.isArray(entry.hashes)) hashes = entry.hashes
1696
+ else continue
1697
+ } else {
1698
+ hashes = [...scanned]
1699
+ ledger.sessions[id] = { revision, hashes, scannedAt: now }
1700
+ rescanned += 1
1701
+ }
1702
+ }
1703
+ for (const hash of hashes) referenced.add(hash)
1704
+ }
1705
+
1706
+ // ── safety interlocks (portability) ───────────────────────────────────────
1707
+ // The layout and the attachment-id vocabulary are Host-owned. On another platform
1708
+ // (HarmonyOS / mobile / a future store version) either may differ; sweeping then
1709
+ // must fail closed instead of treating "nothing referenced" as "everything stale".
1710
+ const blobs = await listAttachmentBlobs(attachmentsRoot)
1711
+ if (blobs.length === 0) {
1712
+ return { skipped: 'no-attachment-objects', attachmentsRoot }
1713
+ }
1714
+ if (referenced.size === 0) {
1715
+ return {
1716
+ skipped: 'no-attachment-references',
1717
+ objects: blobs.length,
1718
+ storedSessions: alive.size,
1719
+ rescanned,
1720
+ scanFailures: scannedFailures,
1721
+ }
1722
+ }
1723
+
1724
+ // Stamp sessions that vanished since the previous tick.
1725
+ let markedOrphaned = 0
1726
+ for (const [id, entry] of Object.entries(ledger.sessions)) {
1727
+ if (alive.has(id) || liveSessionIds.has(id)) continue
1728
+ if (!entry) continue
1729
+ if (!(Number(entry.orphanedAt) > 0)) {
1730
+ entry.orphanedAt = now
1731
+ markedOrphaned += 1
1732
+ }
1733
+ }
1734
+
1735
+ const graceDays = attachmentCleanupDays
1736
+ const due = new Map()
1737
+ for (const [id, entry] of Object.entries(ledger.sessions)) {
1738
+ if (!entry || alive.has(id) || liveSessionIds.has(id)) continue
1739
+ const orphanedAt = Number(entry.orphanedAt) || 0
1740
+ if (!(orphanedAt > 0)) continue
1741
+ if (now - orphanedAt < graceDays * DAY_MS) continue
1742
+ due.set(id, entry)
1743
+ }
1744
+
1745
+ const deleted = []
1746
+ let freedBytes = 0
1747
+ let skippedRecent = 0
1748
+ let skippedReferenced = 0
1749
+ const drop = async (hash, reason) => {
1750
+ const blobPath = join(attachmentsRoot, 'v1', 'objects', hash.slice(0, 2), hash)
1751
+ let info
1752
+ try {
1753
+ info = await stat(blobPath)
1754
+ } catch {
1755
+ return false
1756
+ }
1757
+ if (now - info.mtimeMs < ATTACHMENT_MIN_AGE_MS) {
1758
+ skippedRecent += 1
1759
+ return false
1760
+ }
1761
+ if (!dryRun) {
1762
+ try {
1763
+ await rm(blobPath, { force: true })
1764
+ } catch {
1765
+ return false
1766
+ }
1767
+ }
1768
+ deleted.push({ hash, bytes: info.size, reason })
1769
+ freedBytes += info.size
1770
+ return true
1771
+ }
1772
+
1773
+ for (const entry of due.values()) {
1774
+ for (const hash of entry.hashes ?? []) {
1775
+ if (referenced.has(hash)) {
1776
+ skippedReferenced += 1
1777
+ continue
1778
+ }
1779
+ await drop(hash, 'session-deleted')
1780
+ }
1781
+ }
1782
+
1783
+ const known = new Set()
1784
+ for (const entry of Object.values(ledger.sessions)) {
1785
+ for (const hash of entry?.hashes ?? []) known.add(hash)
1786
+ }
1787
+ let sweptOrphans = 0
1788
+ if (attachmentSweepOrphans) {
1789
+ for (const blob of blobs) {
1790
+ if (referenced.has(blob.hash) || known.has(blob.hash)) continue
1791
+ if (now - blob.mtime < graceDays * DAY_MS) continue
1792
+ if (await drop(blob.hash, 'unreferenced')) sweptOrphans += 1
1793
+ }
1794
+ }
1795
+
1796
+ if (!dryRun) {
1797
+ for (const id of due.keys()) delete ledger.sessions[id]
1798
+ ledger.lastSweepAt = now
1799
+ await writeAttachmentLedger(attachmentLedgerPath, ledger)
1800
+ if (deleted.length > 0) {
1801
+ try {
1802
+ await appendFile(
1803
+ attachmentGcLogPath,
1804
+ `${JSON.stringify({ at: new Date(now).toISOString(), trigger, deleted })}\n`,
1805
+ 'utf8',
1806
+ )
1807
+ } catch {
1808
+ /* audit log is best-effort */
1809
+ }
1810
+ }
1811
+ }
1812
+
1813
+ const report = {
1814
+ dryRun,
1815
+ storedSessions: alive.size,
1816
+ objects: blobs.length,
1817
+ rescanned,
1818
+ scanFailures: scannedFailures,
1819
+ referencedBlobs: referenced.size,
1820
+ markedOrphaned,
1821
+ dueSessions: due.size,
1822
+ deleted: deleted.length,
1823
+ freedBytes,
1824
+ sweptOrphans,
1825
+ skippedRecent,
1826
+ skippedReferenced,
1827
+ }
1828
+ if (report.deleted > 0 || report.markedOrphaned > 0) {
1829
+ console.info(
1830
+ `[session-task-tmpdir] attachments(${trigger})${dryRun ? ' dry-run' : ''}: ` +
1831
+ `deleted ${report.deleted} (${(freedBytes / 1048576).toFixed(1)} MB), ` +
1832
+ `marked ${report.markedOrphaned}, due sessions ${report.dueSessions}, ` +
1833
+ `referenced ${report.referencedBlobs}, rescanned ${report.rescanned}`,
1834
+ )
1835
+ }
1836
+ return report
1837
+ }
1838
+
1839
+ async function runCleanup(trigger, { dryRun = cleanupDryRun, withAttachments = true } = {}) {
1840
+ if (cleaning || !(orphanCleanupDays > 0)) return undefined
1841
+ cleaning = true
1842
+ try {
1843
+ const roots = new Set()
1844
+ try {
1845
+ const defaultDir = ctx.workingDirectory.defaultDirectory
1846
+ if (typeof defaultDir === 'string' && defaultDir) roots.add(defaultDir)
1847
+ } catch {
1848
+ /* no default directory */
1849
+ }
1850
+ const liveSessionIds = []
1851
+ try {
1852
+ for (const session of ctx.sessions.list()) {
1853
+ liveSessionIds.push(String(session.id))
1854
+ const dir = cwdOf(session)
1855
+ if (dir) roots.add(dir)
1856
+ }
1857
+ } catch {
1858
+ /* sessions unavailable this tick */
1859
+ }
1860
+ try {
1861
+ for (const workspace of workspaceRegistry?.list() ?? []) {
1862
+ if (workspace?.path) roots.add(workspace.path)
1863
+ }
1864
+ } catch {
1865
+ /* registry unavailable this tick */
1866
+ }
1867
+ const existingSessionIds = await collectPersistedSessionIds()
1868
+ const report = await cleanupOrphanedTempDirs({
1869
+ roots,
1870
+ rootDirName,
1871
+ orphanDays: orphanCleanupDays,
1872
+ dryRun,
1873
+ liveSessionIds,
1874
+ existingSessionIds,
1875
+ log: (message) => console.info(`[session-task-tmpdir] ${message}`),
1876
+ })
1877
+ if (
1878
+ report.deleted.length > 0 ||
1879
+ report.markedOrphaned.length > 0 ||
1880
+ report.kept.error > 0
1881
+ ) {
1882
+ console.info(
1883
+ `[session-task-tmpdir] cleanup(${trigger})${report.dryRun ? ' dry-run' : ''}: ` +
1884
+ `deleted ${report.deleted.length}, marked ${report.markedOrphaned.length}, ` +
1885
+ `kept live ${report.kept.live} / alive ${report.kept.alive} / waiting ${report.kept.waiting} / ` +
1886
+ `unmarked ${report.kept.unmarked} / errors ${report.kept.error}`,
1887
+ )
1888
+ }
1889
+ // Attachment store sweep (v0.6): same tick, same 7-day semantics.
1890
+ if (withAttachments) {
1891
+ try {
1892
+ report.attachments = await runAttachmentCleanup(trigger, { dryRun })
1893
+ } catch (error) {
1894
+ console.warn('[session-task-tmpdir] attachment cleanup failed:', error?.message ?? error)
1895
+ report.attachments = { error: String(error?.message ?? error) }
1896
+ }
1897
+ }
1898
+ return report
1899
+ } catch (error) {
1900
+ console.warn('[session-task-tmpdir] cleanup failed:', error?.message ?? error)
1901
+ return undefined
1902
+ } finally {
1903
+ cleaning = false
1904
+ }
1905
+ }
1906
+
1907
+ if (orphanCleanupDays > 0) {
1908
+ ctx.effect(() => {
1909
+ const startupTimer = setTimeout(() => {
1910
+ void runCleanup('startup')
1911
+ }, STARTUP_CLEANUP_DELAY_MS)
1912
+ const interval = setInterval(() => {
1913
+ void runCleanup('interval')
1914
+ }, cleanupIntervalHours * 3_600_000)
1915
+ return () => {
1916
+ clearTimeout(startupTimer)
1917
+ clearInterval(interval)
1918
+ }
1919
+ }, 'session-task-tmpdir: cleanup schedule')
1920
+ }
1921
+
1922
+ // ── prompt convention + tool ────────────────────────────────────────────────
1923
+ ctx.effect(() =>
1924
+ ctx.systemPrompt.context({
1925
+ name: 'session-task-tmpdir',
1926
+ order: 900,
1927
+ text: [
1928
+ '## Task temp folder (session-task-tmpdir)',
1929
+ '',
1930
+ `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
+ '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
+ '',
1933
+ '### Long-term files need the user’s approval first',
1934
+ '',
1935
+ '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
+ rootDirName +
1937
+ '/` 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:`,
1939
+ '- A. 不长期保存',
1940
+ '- B. 工作区根目录保存',
1941
+ `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).',
1944
+ '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)'}.`,
1949
+ '',
1950
+ '### What the write guard covers (v0.7)',
1951
+ '',
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.',
1958
+ '',
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).`,
1960
+ ].join('\n'),
1961
+ }),
1962
+ )
1963
+
1964
+ ctx.effect(() =>
1965
+ ctx.tools.register({
1966
+ name: 'task_tmpdir',
1967
+ 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.`,
1968
+ parameters: {
1969
+ type: 'object',
1970
+ properties: {
1971
+ sub: { type: 'string', description: 'Optional subdirectory under the task temp directory.' },
1972
+ },
1973
+ additionalProperties: false,
1974
+ },
1975
+ output: {
1976
+ schema: {
1977
+ type: 'object',
1978
+ properties: {
1979
+ path: { type: 'string' },
1980
+ title: { type: 'string' },
1981
+ },
1982
+ required: ['path', 'title'],
1983
+ },
1984
+ render: (_args, value) => [{ type: 'text', text: String(value?.path ?? '') }],
1985
+ },
1986
+ async execute(args, exec) {
1987
+ const agent = exec?.agent
1988
+ const session = agent ? ctx.sessions.get(agent.id) : undefined
1989
+ if (!session) throw new Error('task_tmpdir: no live session for this tool call')
1990
+ const result = await createDir(session, args?.sub)
1991
+ return result
1992
+ },
1993
+ }),
1994
+ )
1995
+
1996
+ // Long-term destination approval. The model may only call this after the user
1997
+ // picked a location (multiple-choice question) or after the task itself named it.
1998
+ ctx.effect(() =>
1999
+ ctx.tools.register({
2000
+ name: 'longterm_approve',
2001
+ description:
2002
+ '登记「本次会话已获用户同意的长期保存落点」。用户明确同意长期保存(或任务里已指定位置)后调用;' +
2003
+ `登记后 write/edit、shell 命令、publish 交付、python 等代码工具才能写该目录(工作区内或工作区外都可以),` +
2004
+ `否则会被拒绝并提示先问用户。临时产物不要用它,直接用 task_tmpdir 写 ${rootDirName}/<会话标题>/。`,
2005
+ parameters: {
2006
+ type: 'object',
2007
+ properties: {
2008
+ path: { type: 'string', description: '用户指定/同意的目录绝对路径(传文件路径也行,会自动取所在目录)。' },
2009
+ reason: { type: 'string', description: '为什么属于长期保存(一句话,用于日志)。' },
2010
+ basis: {
2011
+ type: 'string',
2012
+ enum: ['user_confirmed', 'task_designated'],
2013
+ description: 'user_confirmed=用户刚在选择题里同意长期保存;task_designated=用户在任务里明确指定了该位置。',
2014
+ },
2015
+ },
2016
+ required: ['path'],
2017
+ additionalProperties: false,
2018
+ },
2019
+ output: {
2020
+ schema: {
2021
+ type: 'object',
2022
+ properties: {
2023
+ approved: { type: 'boolean' },
2024
+ path: { type: 'string' },
2025
+ basis: { type: 'string' },
2026
+ approvedPrefixes: { type: 'array', items: { type: 'string' } },
2027
+ },
2028
+ required: ['approved', 'path'],
2029
+ },
2030
+ render: (_args, value) => [
2031
+ { type: 'text', text: `approved: ${String(value?.path ?? '')}` },
2032
+ ],
2033
+ },
2034
+ async execute(args, exec) {
2035
+ const agent = exec?.agent
2036
+ const session = agent ? ctx.sessions.get(agent.id) : undefined
2037
+ if (!session) throw new Error('longterm_approve: no live session for this tool call')
2038
+ const cwd = cwdOf(session)
2039
+ if (!cwd) throw new Error('longterm_approve: session working directory is unavailable')
2040
+ const raw = typeof args?.path === 'string' ? args.path.trim() : ''
2041
+ if (!raw) throw new Error('longterm_approve: path 不能为空')
2042
+ const expanded = expandTildePath(raw)
2043
+ const abs = isAbsolute(expanded) ? resolve(expanded) : resolve(cwd, expanded)
2044
+ const tmpRoot = baseDir(cwd)
2045
+ if (samePath(abs, tmpRoot) || pathInside(tmpRoot, abs)) {
2046
+ throw new Error(`longterm_approve: ${rootDirName}/ 是临时目录,不需要也不允许登记`)
2047
+ }
2048
+ if (isScratchPath(abs, rootDirName)) {
2049
+ throw new Error(`longterm_approve: 路径包含 ${rootDirName}/ 临时目录段,不需要也不允许登记`)
2050
+ }
2051
+ // v0.7 (review A9): registering the workspace root itself would whitelist the
2052
+ // whole workspace, so it is refused like a filesystem root.
2053
+ if (samePath(abs, cwd)) {
2054
+ throw new Error('longterm_approve: 不能登记会话工作区根目录本身,请指定工作区内的具体子目录(或工作区外的目录)')
2055
+ }
2056
+ const insideWorkspace = pathInside(cwd, abs)
2057
+ if (!insideWorkspace) {
2058
+ // v0.7: a destination outside the workspace (e.g. HarmonyOS
2059
+ // `Download/<package>/`) can be registered too, but never a filesystem
2060
+ // root, a whole drive or the user's home directory.
2061
+ const segments = abs.replace(/[\\/]+$/, '').split(/[\\/]+/).filter(Boolean)
2062
+ let fsRoot
2063
+ try {
2064
+ fsRoot = parse(abs).root
2065
+ } catch {
2066
+ fsRoot = undefined
2067
+ }
2068
+ if ((fsRoot && samePath(abs, fsRoot)) || samePath(abs, homedir()) || segments.length < 2) {
2069
+ throw new Error('longterm_approve: 不能登记磁盘根目录、用户主目录或层级过浅的目录,请指定具体文件夹')
2070
+ }
2071
+ }
2072
+ 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)
2081
+ }
2082
+ } catch {
2083
+ // keep the passed path
2084
+ }
2085
+ const list = registerApproval(session, directory, { reason: args?.reason, basis })
2086
+ return {
2087
+ approved: true,
2088
+ path: directory,
2089
+ basis,
2090
+ approvedPrefixes: list.map((entry) => entry.prefix),
2091
+ }
2092
+ },
2093
+ }),
2094
+ )
2095
+
2096
+ // Manual cleanup trigger (also handy for verifying the scheduled pass).
2097
+ ctx.effect(() =>
2098
+ ctx.tools.register({
2099
+ 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, and (v0.6) the attachment store reclaims the blobs of sessions deleted more than ${attachmentCleanupDays} days ago; everything else is reported as kept. Pass dryRun to only report.`,
2100
+ parameters: {
2101
+ type: 'object',
2102
+ properties: {
2103
+ dryRun: { type: 'boolean', description: 'Only report what would be marked or deleted.' },
2104
+ attachments: { type: 'boolean', description: 'Also sweep the attachment store (default true).' },
2105
+ },
2106
+ additionalProperties: false,
2107
+ },
2108
+ output: {
2109
+ schema: {
2110
+ type: 'object',
2111
+ properties: {
2112
+ disabled: { type: 'boolean' },
2113
+ dryRun: { type: 'boolean' },
2114
+ deleted: { type: 'number' },
2115
+ markedOrphaned: { type: 'number' },
2116
+ kept: { type: 'object' },
2117
+ attachments: { type: 'object' },
2118
+ },
2119
+ },
2120
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
2121
+ },
2122
+ async execute(args) {
2123
+ const withAttachments = args?.attachments !== false
2124
+ const report = await runCleanup('manual', { dryRun: args?.dryRun === true, withAttachments })
2125
+ if (!report) return { disabled: true, dryRun: false, deleted: 0, markedOrphaned: 0, kept: {} }
2126
+ const value = {
2127
+ disabled: false,
2128
+ dryRun: report.dryRun,
2129
+ deleted: report.deleted.length,
2130
+ markedOrphaned: report.markedOrphaned.length,
2131
+ kept: report.kept,
2132
+ paths: report.deleted.map((entry) => entry.path),
2133
+ }
2134
+ if (report.attachments) {
2135
+ const a = report.attachments
2136
+ value.attachments = a.skipped || a.error
2137
+ ? a
2138
+ : {
2139
+ dryRun: Boolean(a.dryRun),
2140
+ deleted: a.deleted ?? 0,
2141
+ freedMb: Number(((a.freedBytes ?? 0) / 1048576).toFixed(1)),
2142
+ dueSessions: a.dueSessions ?? 0,
2143
+ storedSessions: a.storedSessions ?? 0,
2144
+ objects: a.objects ?? 0,
2145
+ referencedBlobs: a.referencedBlobs ?? 0,
2146
+ markedOrphaned: a.markedOrphaned ?? 0,
2147
+ sweptOrphans: a.sweptOrphans ?? 0,
2148
+ skippedRecent: a.skippedRecent ?? 0,
2149
+ skippedReferenced: a.skippedReferenced ?? 0,
2150
+ }
2151
+ }
2152
+ return value
2153
+ },
2154
+ }),
2155
+ )
2156
+
2157
+ // ── write guard (v0.5 root rules, v0.7 capability channels) ────────────────
2158
+ // Scratch files keep the v1 rules (temp-named files in the working-directory root
2159
+ // and files directly under `<rootDirName>/` are denied). Long-term artifacts
2160
+ // additionally require a session approval: `write`/`edit`, shell commands,
2161
+ // delivery copies made by `publish`, embedded code runtimes and other tools that
2162
+ // declare path arguments may not create anything outside `<rootDirName>/` (or
2163
+ // outside the workspace) until the model has asked the user and registered the
2164
+ // chosen directory with `longterm_approve`.
2165
+ if (guardWorkspaceRoot || requireApprovalOutsideTmp) {
2166
+ ctx.effect(
2167
+ () =>
2168
+ ctx.tools.guard((execution) => {
2169
+ try {
2170
+ if (!execution) return undefined
2171
+ const toolName = String(execution.name ?? '')
2172
+ const args = execution.arguments && typeof execution.arguments === 'object' ? execution.arguments : undefined
2173
+ if (!args) return undefined
2174
+ const agent = execution.agent
2175
+ if (!agent) return undefined
2176
+ const session = ctx.sessions.get(agent.id)
2177
+ if (!session) return undefined
2178
+ const cwd = cwdOf(session)
2179
+ if (!cwd) return undefined
2180
+ let schema = execution.schema
2181
+ if (!schema || typeof schema !== 'object') {
2182
+ try {
2183
+ schema = ctx.tools.get(toolName, agent)
2184
+ } catch {
2185
+ schema = undefined
2186
+ }
2187
+ }
2188
+ const plan = toolWritePlan(toolName, args, {
2189
+ writeToolNames,
2190
+ publishToolNames,
2191
+ codeToolNames,
2192
+ shellToolNames,
2193
+ guardCodeTools,
2194
+ guardUnknownTools,
2195
+ guardPublish: publishGuard !== 'off',
2196
+ schema,
2197
+ })
2198
+ if (plan.channel === 'skip') return undefined
2199
+
2200
+ // v0.7 (review M5): only the v1 "workspace-root" rules depend on the session
2201
+ // working directory being a registered workspace root. Destinations outside
2202
+ // the workspace are checked even when the session `cd`-ed into a subfolder.
2203
+ const protectedRoot = isProtectedRoot(cwd)
2204
+ const approvedPrefixes = approvedPrefixesFor(session)
2205
+ const classifyOptions = {
2206
+ rootDirName,
2207
+ allowRootPatterns,
2208
+ allowRootFiles,
2209
+ approvedPrefixes,
2210
+ outsideAllow,
2211
+ requireApprovalOutsideTmp,
2212
+ guardOutsideWorkspace,
2213
+ }
2214
+ const deny = (label, reason) => {
2215
+ console.info(`[session-task-tmpdir] ${label} denied: ${reason}`)
2216
+ return reason
2217
+ }
2218
+ const outsideWarn = (label, abs) => {
2219
+ console.info(`[session-task-tmpdir] ${label} (warn): ${abs}`)
2220
+ }
2221
+
2222
+ // write/edit: scratch rules first (v0.5), then the long-term classification
2223
+ if (plan.channel === 'write') {
2224
+ const targetPath = firstWriteTarget(args)
2225
+ if (!targetPath) return undefined
2226
+ // v0.8 claim-on-write: `<rootDirName>/<dir>/…` is always allowed, so the
2227
+ // claim can run before the long-term checks below.
2228
+ claimTmpTargets([targetPath], session)
2229
+ if (guardWorkspaceRoot && protectedRoot) {
2230
+ const scratchReason = workspaceRootGuardReason(targetPath, cwd, rootDirName)
2231
+ if (scratchReason) return deny(`${toolName} guard`, scratchReason)
2232
+ }
2233
+ const verdict = classifyWriteTarget(targetPath, cwd, classifyOptions)
2234
+ if (verdict.kind === 'inside-longterm') {
2235
+ if (!protectedRoot) return undefined
2236
+ return deny('longterm guard', verdict.reason)
2237
+ }
2238
+ if (verdict.kind === 'outside') {
2239
+ if (guardOutsideWorkspace === 'warn') {
2240
+ outsideWarn('outside guard', verdict.abs)
2241
+ return undefined
2242
+ }
2243
+ if (guardOutsideWorkspace === 'off') return undefined
2244
+ return deny('outside guard', outsideWriteDenialReason(verdict.abs, { rootDirName }))
2245
+ }
2246
+ return undefined
2247
+ }
2248
+
2249
+ // publish: the tool copies a finished artifact into a delivery folder
2250
+ if (plan.channel === 'publish') {
2251
+ const publishBase =
2252
+ typeof publishBaseDir === 'string' && publishBaseDir.trim() ? resolve(cwd, publishBaseDir.trim()) : undefined
2253
+ for (const target of publishWriteTargets(args)) {
2254
+ const verdict = classifyWriteTarget(target, cwd, {
2255
+ ...classifyOptions,
2256
+ baseDir: publishBase,
2257
+ })
2258
+ if (verdict.kind !== 'inside-longterm' && verdict.kind !== 'outside') continue
2259
+ if (verdict.kind === 'inside-longterm' && !protectedRoot) continue
2260
+ if (publishGuard === 'warn') {
2261
+ outsideWarn('publish guard', verdict.abs)
2262
+ continue
2263
+ }
2264
+ const reason =
2265
+ verdict.kind === 'outside'
2266
+ ? outsideWriteDenialReason(verdict.abs, { rootDirName, action: '发布' })
2267
+ : `${verdict.reason}(发布目标:${verdict.abs})`
2268
+ return deny('publish guard', `publish 会把文件复制到长期位置:${reason}`)
2269
+ }
2270
+ claimTmpTargets(publishWriteTargets(args), session)
2271
+ return undefined
2272
+ }
2273
+
2274
+ // code tools (python/node/…): best-effort static scan of write statements
2275
+ if (plan.channel === 'code') {
2276
+ const code = codeTextOf(args)
2277
+ if (!code) return undefined
2278
+ const scanned = []
2279
+ const reason = codeToolGuardReason(code, cwd, {
2280
+ ...classifyOptions,
2281
+ guardOutsideWorkspace,
2282
+ skipInside: !protectedRoot,
2283
+ onTarget: (abs) => scanned.push(abs),
2284
+ })
2285
+ if (reason) return deny('code guard', reason)
2286
+ claimTmpTargets(scanned, session)
2287
+ return undefined
2288
+ }
2289
+
2290
+ // shell tools: literal-path scan of commands that create something
2291
+ if (plan.channel === 'shell') {
2292
+ if (commandGuard === 'off') return undefined
2293
+ const command = typeof args.command === 'string' ? args.command : undefined
2294
+ if (!command) return undefined
2295
+ const commandBase =
2296
+ typeof args.workdir === 'string' && args.workdir.trim() ? resolve(cwd, args.workdir) : cwd
2297
+ const scanned = []
2298
+ const reason = longtermCommandGuardReason(command, cwd, {
2299
+ ...classifyOptions,
2300
+ baseDir: commandBase,
2301
+ skipInside: !protectedRoot,
2302
+ onTarget: (abs) => scanned.push(abs),
2303
+ })
2304
+ if (reason && commandGuard !== 'warn') return deny('command guard', reason)
2305
+ if (reason) console.info(`[session-task-tmpdir] command guard (warn) ${reason}`)
2306
+ // v0.8: absolute tokens plus relative `<rootDirName>/…` mentions.
2307
+ claimTmpTargets([...scanned, ...relativeTmpTargets(command)], session, {
2308
+ allowDirItself: commandCreatesDirectory(command),
2309
+ })
2310
+ return undefined
2311
+ }
2312
+
2313
+ // unknown but write-capable tools: only the two high-risk destinations
2314
+ if (plan.channel === 'unknown') {
2315
+ for (const target of collectPathTargets(args, { schema })) {
2316
+ const verdict = classifyWriteTarget(target, cwd, classifyOptions)
2317
+ if (verdict.kind === 'outside') {
2318
+ if (guardOutsideWorkspace === 'warn') {
2319
+ outsideWarn('outside guard', verdict.abs)
2320
+ continue
2321
+ }
2322
+ if (guardOutsideWorkspace === 'off') continue
2323
+ return deny('outside guard', outsideWriteDenialReason(verdict.abs, { rootDirName }))
2324
+ }
2325
+ if (verdict.kind === 'inside-longterm' && protectedRoot && samePath(dirname(verdict.abs), resolve(cwd))) {
2326
+ return deny('longterm guard', verdict.reason)
2327
+ }
2328
+ }
2329
+ claimTmpTargets(collectPathTargets(args, { schema }), session)
2330
+ return undefined
2331
+ }
2332
+ return undefined
2333
+ } catch {
2334
+ return undefined
2335
+ }
2336
+ }),
2337
+ 'session-task-tmpdir: write guard',
2338
+ )
2339
+ }
2340
+ }