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

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