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

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