dsh-delete-session 0.2.5 → 0.2.6

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/src/index.js CHANGED
@@ -1,2159 +1,2168 @@
1
- // dsh-delete-session - host half.
2
- //
3
- // Loopback-only HTTP routes serve the client half:
4
- //
5
- // POST /dsh-delete-session/delete { sessionId }
6
- //
7
- // Deletion pipeline, kept consistent with the live DSH services so in-memory
8
- // state and on-disk units cannot disagree after the request returns:
9
- //
10
- // 1. stop a running agent (cancel + time-boxed quiescence) when one exists;
11
- // 2. flush and detach the live session so its async dispose cannot rewrite
12
- // the log directory after we remove it, and wait for the persistence
13
- // retirement that session/disposed starts;
14
- // 3. take the persistence write lease briefly: a busy lease means the
15
- // session is still open in DSH, so the request is refused with 409
16
- // instead of racing the active writer;
17
- // 4. remove every on-disk session directory (raw id and session- prefix);
18
- // 5. verify through the persistence service and a directory re-scan;
19
- // 6. detach the session from workspace accounting so the sidebar drops the
20
- // row instead of re-grouping an orphan under "Ungrouped".
21
- //
22
- // The plugin imports nothing from the DSH SDK: every service is resolved
23
- // through the cordis context at call time, so the module loads on any profile
24
- // and degrades to the filesystem path when a service is absent.
25
- import { spawn } from 'node:child_process'
26
- import fs from 'node:fs'
27
- import os from 'node:os'
28
- import path from 'node:path'
29
- import { promisify } from 'node:util'
30
-
31
- /** The asynchronous face of `fs`, used wherever a blocking call could stall the server. */
32
- const fsp = fs.promises
33
- /** The same underlying call as `fs.realpathSync.native`, just not blocking. */
34
- const realpathNative = promisify(fs.realpath.native)
35
-
36
- export const name = 'dsh-delete-session'
37
-
38
- const ROUTE_PREFIX = '/dsh-delete-session'
39
- const SESSION_ID_RE = /^(session-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
40
- const MAX_BATCH = 100
41
-
42
- class HttpError extends Error {
43
- constructor(status, code, message) {
44
- super(message)
45
- this.status = status
46
- this.code = code
47
- }
48
- }
49
-
50
- // --- paths -------------------------------------------------------------------
51
-
52
- function dshHome() {
53
- return process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
54
- }
55
-
56
- function sessionsRoot() {
57
- return path.join(dshHome(), 'sessions')
58
- }
59
-
60
- // A session id travels in two spellings: the raw uuid and `session-<uuid>`.
61
- // The on-disk JSONL backend uses the prefixed form for the directory name,
62
- // while workspace and projection rows may carry either. Clean both.
63
- function idVariants(sessionId) {
64
- const out = new Set([sessionId])
65
- if (sessionId.startsWith('session-')) out.add(sessionId.slice('session-'.length))
66
- else out.add(`session-${sessionId}`)
67
- return [...out]
68
- }
69
- /** The bare uuid, for comparing ids that may or may not carry the prefix. */
70
- function bareSessionId(sessionId) {
71
- return sessionId.startsWith('session-') ? sessionId.slice('session-'.length) : sessionId
72
- }
73
-
74
- /**
75
- * Every session header the host knows about, or `[]` when no service can list
76
- * them. `sessionQuery` merges live and persisted sessions and carries
77
- * `parentSession`, so the parent/child map never has to be decoded out of the
78
- * zstd logs.
79
- */
80
- async function listSessionHeaders(ctx) {
81
- try {
82
- const query = ctx.get('sessionQuery')
83
- if (query && typeof query.listSessions === 'function') {
84
- const records = await query.listSessions()
85
- const headers = records
86
- .map((record) => record && record.header)
87
- .filter((header) => header && typeof header.id === 'string')
88
- if (headers.length > 0) return headers
89
- }
90
- } catch {
91
- // fall through to the persistence service
92
- }
93
- try {
94
- const persistence = ctx.get('sessionPersistence')
95
- if (persistence && typeof persistence.list === 'function') {
96
- const snapshots = await persistence.list({})
97
- return snapshots
98
- .map((snapshot) => snapshot && snapshot.header)
99
- .filter((header) => header && typeof header.id === 'string')
100
- }
101
- } catch {
102
- // no service can list sessions on this host
103
- }
104
- return []
105
- }
106
-
107
- /**
108
- * Every descendant of one session, breadth first. A subagent is a session of
109
- * its own — its own directory and its own log — linked only by `parentSession`,
110
- * so a delete that ignores the link leaves orphans behind.
111
- *
112
- * @param headers - the host session headers.
113
- * @param sessionId - the session being deleted.
114
- * @returns descendant headers, parents before their own children.
115
- */
116
- function collectDescendants(headers, sessionId) {
117
- const byParent = new Map()
118
- for (const header of headers) {
119
- if (typeof header.parentSession !== 'string') continue
120
- // Only subagents belong to a parent. A fork records where it branched from,
121
- // but it is a conversation of its own and the user can open it like any other:
122
- // sweeping those up deletes work nobody asked to delete.
123
- if (header.origin !== 'subagent') continue
124
- const key = bareSessionId(header.parentSession)
125
- const list = byParent.get(key)
126
- if (list === undefined) byParent.set(key, [header])
127
- else list.push(header)
128
- }
129
- const found = []
130
- const seen = new Set([bareSessionId(sessionId)])
131
- const queue = [bareSessionId(sessionId)]
132
- while (queue.length > 0) {
133
- const current = queue.shift()
134
- for (const child of byParent.get(current) ?? []) {
135
- const key = bareSessionId(child.id)
136
- if (seen.has(key)) continue
137
- seen.add(key)
138
- found.push(child)
139
- queue.push(key)
140
- }
141
- }
142
- return found
143
- }
144
-
145
- /**
146
- * Sessions whose parent no longer exists. Deleting a parent used to leave these
147
- * on disk, and the sidebar cannot show the ones that never joined a workspace.
148
- */
149
- function collectOrphans(headers) {
150
- const present = new Set(headers.map((entry) => bareSessionId(entry.id)))
151
- // Same rule as the descendant walk: a fork whose source is gone is still a
152
- // conversation of its own, not an abandoned child.
153
- return headers.filter((entry) => entry.origin === 'subagent'
154
- && typeof entry.parentSession === 'string'
155
- && !present.has(bareSessionId(entry.parentSession)))
156
- }
157
-
158
- /**
159
- * The child list the dialog shows: identity, nesting depth and the project the
160
- * subagent ran in, so the names are recognisable before anything is ticked.
161
- */
162
- function describeChildren(headers, sessionId) {
163
- const byBare = new Map(headers.map((entry) => [bareSessionId(entry.id), entry]))
164
- return collectDescendants(headers, sessionId).map((entry) => {
165
- let depth = 1
166
- let cursor = entry
167
- while (typeof cursor.parentSession === 'string') {
168
- const parent = byBare.get(bareSessionId(cursor.parentSession))
169
- if (parent === undefined || bareSessionId(parent.id) === bareSessionId(sessionId)) break
170
- depth += 1
171
- cursor = parent
172
- }
173
- return {
174
- id: entry.id,
175
- depth,
176
- cwd: typeof entry.cwd === 'string' ? entry.cwd : undefined,
177
- }
178
- })
179
- }
180
-
181
- /**
182
- * The children the caller asked to delete, narrowed to real descendants. A
183
- * stale or unrelated id is dropped instead of failing the delete: the parent is
184
- * the session the user clicked, and that click must still land.
185
- *
186
- * @returns the descendants' own ids, in the order they were asked for.
187
- */
188
- function selectChildDeletes(headers, sessionId, requested) {
189
- if (!Array.isArray(requested) || requested.length === 0) return []
190
- const descendants = new Map()
191
- for (const entry of collectDescendants(headers, sessionId)) {
192
- descendants.set(bareSessionId(entry.id), entry.id)
193
- }
194
- const picked = []
195
- for (const id of requested) {
196
- if (typeof id !== 'string' || id === '') continue
197
- const hit = descendants.get(bareSessionId(id))
198
- if (hit !== undefined && !picked.includes(hit)) picked.push(hit)
199
- }
200
- return picked
201
- }
202
-
203
- // Scan every workspace directory under $DSH_HOME/sessions for the session's
204
- // directories, so the workspace-path encoding never has to be re-derived here.
205
- function findSessionDirs(sessionId) {
206
- const root = sessionsRoot()
207
- let entries
208
- try {
209
- entries = fs.readdirSync(root, { withFileTypes: true })
210
- } catch {
211
- return []
212
- }
213
- const variants = idVariants(sessionId)
214
- const found = []
215
- for (const entry of entries) {
216
- if (!entry.isDirectory()) continue
217
- for (const variant of variants) {
218
- const candidate = path.join(root, entry.name, variant)
219
- try {
220
- if (fs.statSync(candidate).isDirectory() && !found.includes(candidate)) found.push(candidate)
221
- } catch {
222
- // keep scanning
223
- }
224
- }
225
- }
226
- return found
227
- }
228
-
229
- /**
230
- * The C# behind the cached recycle helper. One process handles every path of a
231
- * delete (the session directory and its cache rows), because each PowerShell
232
- * start costs the better part of a second and a delete used to pay it twice.
233
- */
234
- const RECYCLE_CSHARP = `using System;
235
- using System.IO;
236
- using Microsoft.VisualBasic.FileIO;
237
-
238
- public static class Program {
239
- public static int Main(string[] args) {
240
- int done = 0;
241
- foreach (string target in args) {
242
- try {
243
- if (Directory.Exists(target)) {
244
- FileSystem.DeleteDirectory(target, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
245
- } else if (File.Exists(target)) {
246
- FileSystem.DeleteFile(target, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
247
- }
248
- done++;
249
- } catch {
250
- // leave it: the caller verifies the path is gone
251
- }
252
- }
253
- return done == args.Length ? 0 : 1;
254
- }
255
- }`
256
-
257
- /** Bump when `RECYCLE_CSHARP` changes, so a cached build is not reused. */
258
- const RECYCLE_EXE_VERSION = 1
259
- const RECYCLE_TIMEOUT_MS = 60 * 1000
260
-
261
- /** The C# compiler that ships with .NET Framework, if this machine has it. */
262
- function findCsc() {
263
- const windir = process.env.WINDIR || 'C:\\Windows'
264
- for (const flavor of ['Framework64', 'Framework']) {
265
- const candidate = path.join(windir, 'Microsoft.NET', flavor, 'v4.0.30319', 'csc.exe')
266
- try {
267
- if (fs.statSync(candidate).isFile()) return candidate
268
- } catch {
269
- // try the next flavour
270
- }
271
- }
272
- return null
273
- }
274
-
275
- /** Compile the recycle helper once into the DSH cache; null when it cannot. */
276
- async function ensureRecycleExe() {
277
- if (process.platform !== 'win32') return null
278
- const dir = path.join(dshHome(), 'cache', 'dsh-delete-session', `v${RECYCLE_EXE_VERSION}`)
279
- const exe = path.join(dir, 'dsh-recycle.exe')
280
- if (await pathExists(exe)) return exe
281
- const csc = findCsc()
282
- if (csc === null) return null
283
- try {
284
- await fsp.mkdir(dir, { recursive: true })
285
- const source = path.join(dir, 'recycle.cs')
286
- await fsp.writeFile(source, RECYCLE_CSHARP, 'utf8')
287
- const built = await runExecutable(csc, ['-nologo', '-target:exe', `-out:${exe}`, '-r:System.dll', '-r:Microsoft.VisualBasic.dll', source], PICK_COMPILE_TIMEOUT_MS)
288
- try { await fsp.rm(source, { force: true }) } catch { /* best effort */ }
289
- if (built.code === 0) {
290
- if (await pathExists(exe)) return exe
291
- }
292
- } catch {
293
- // fall through to the PowerShell path
294
- }
295
- return null
296
- }
297
-
298
- /**
299
- * The command that hands paths to the platform trash.
300
- *
301
- * Windows is done in-process (see `sendToRecycleBin`); macOS has no trash command
302
- * of its own, so Finder performs the delete, and Linux delegates to `gio trash`,
303
- * which ships with GLib on every mainstream desktop. Kept separate from running
304
- * it so the shape can be tested on a machine that has neither.
305
- */
306
- /**
307
- * Compile the helper executables while nothing is waiting for them. The first
308
- * pick or delete otherwise pays for `csc` (0.5-1.7 s); by the time the user
309
- * clicks, the cache is already there.
310
- *
311
- * Deliberately fire-and-forget and never fatal: a machine without `csc` keeps
312
- * the PowerShell fallbacks, and a failure here must not stop the plugin loading.
313
- */
314
- function warmCompiledHelpers() {
315
- if (process.platform !== 'win32') return
316
- const warm = async () => {
317
- try { await ensureRecycleExe() } catch { /* the fallback covers it */ }
318
- }
319
- void warm()
320
- }
321
- function trashCommandFor(platform, targets) {
322
- if (platform === 'darwin') {
323
- // One -e per path: AppleScript has no list form for this, and a failure on one
324
- // path must not stop the rest.
325
- return {
326
- program: 'osascript',
327
- args: targets.flatMap((target) => [
328
- '-e',
329
- `tell application "Finder" to delete (POSIX file "${target.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}")`,
330
- ]),
331
- }
332
- }
333
- return { program: 'gio', args: ['trash', ...targets] }
334
- }
335
-
336
- /**
337
- * Run the platform trash command. Returns false when the command is missing
338
- * (`gio` on a bare container, a denied Finder automation prompt) so the caller
339
- * keeps the staged copy instead of pretending the delete happened.
340
- */
341
- async function trashWithSystem(targets, platform) {
342
- const command = trashCommandFor(platform, targets)
343
- try {
344
- const run = await runExecutable(command.program, command.args, RECYCLE_TIMEOUT_MS)
345
- return run.code === 0
346
- } catch {
347
- return false
348
- }
349
- }
350
-
351
- /**
352
- * Send paths to the Windows Recycle Bin.
353
- *
354
- * A delete has to be undoable, and the Recycle Bin is the undo the user already
355
- * knows. Node has no API for it, and a Node process cannot synthesize the
356
- * `$I`/`$R` pair the Shell owns, so one PowerShell does the work through
357
- * `Microsoft.VisualBasic.FileIO.FileSystem` — the supported managed wrapper of
358
- * "delete with undo". The script prints one verdict per path, so a partial
359
- * failure is reported instead of being assumed away.
360
- *
361
- * @returns `true` only when every path actually left its original location.
362
- */
363
- async function sendToRecycleBin(targets) {
364
- if (targets.length === 0) return true
365
- // macOS and Linux have their own trash; Windows is handled below in-process.
366
- if (process.platform !== 'win32') return trashWithSystem(targets, process.platform)
367
-
368
- // The compiled helper answers in ~100 ms where one PowerShell start costs the
369
- // better part of a second, and it takes every path of a delete at once.
370
- const exe = await ensureRecycleExe()
371
- if (exe !== null) {
372
- try {
373
- const run = await runExecutable(exe, targets, RECYCLE_TIMEOUT_MS)
374
- return run.code === 0
375
- } catch {
376
- return false
377
- }
378
- }
379
-
380
- const list = targets.map((target) => `'${target.replace(/'/g, "''")}'`).join(', ')
381
- const script = [
382
- 'Add-Type -AssemblyName Microsoft.VisualBasic',
383
- `$targets = @(${list})`,
384
- 'foreach ($target in $targets) {',
385
- ' try {',
386
- ' if (Test-Path -LiteralPath $target -PathType Container) {',
387
- ' [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($target,',
388
- ' [Microsoft.VisualBasic.FileIO.UIOption]::OnlyErrorDialogs,',
389
- ' [Microsoft.VisualBasic.FileIO.RecycleOption]::SendToRecycleBin)',
390
- ' } elseif (Test-Path -LiteralPath $target) {',
391
- ' [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($target,',
392
- ' [Microsoft.VisualBasic.FileIO.UIOption]::OnlyErrorDialogs,',
393
- ' [Microsoft.VisualBasic.FileIO.RecycleOption]::SendToRecycleBin)',
394
- ' }',
395
- ' [Console]::Out.WriteLine(\'OK\')',
396
- ' } catch {',
397
- ' [Console]::Out.WriteLine(\'FAIL\')',
398
- ' }',
399
- '}',
400
- ].join('\r\n')
401
-
402
- const scriptPath = path.join(os.tmpdir(), `dsh-delete-session-bin-${process.pid}-${Date.now()}.ps1`)
403
- const bytes = Buffer.concat([Buffer.from([0xEF, 0xBB, 0xBF]), Buffer.from(script, 'utf8')])
404
- let output
405
- try {
406
- await fsp.writeFile(scriptPath, bytes)
407
- output = await runPowershell(
408
- ['-NoProfile', '-STA', '-ExecutionPolicy', 'Bypass', '-File', scriptPath],
409
- SHELL_TIMEOUT_MS,
410
- )
411
- } catch {
412
- return false
413
- } finally {
414
- try { await fsp.rm(scriptPath, { force: true }) } catch { /* best effort */ }
415
- }
416
- const ok = output.split(/\r?\n/).filter((line) => line.trim() === 'OK').length
417
- return ok === targets.length
418
- }
419
-
420
- /**
421
- * Move paths into a fresh `$DSH_HOME/session-trash-<stamp>` folder.
422
- *
423
- * This is the fast half of a retire: a same-volume rename costs microseconds,
424
- * while the shell's recycle operation costs ~600 ms. The caller reports the
425
- * delete as done after this, so the wait never reaches the user.
426
- *
427
- * @returns `{ moved, root }` — the source paths and the staging folder, or a null
428
- * root when the folder could not be created.
429
- */
430
- async function stageToTrash(targets) {
431
- if (targets.length === 0) return { moved: [], root: null }
432
- const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 17)
433
- const root = path.join(dshHome(), `session-trash-${stamp}-${process.pid}-${retireCounter++}`)
434
- try {
435
- await fsp.mkdir(root, { recursive: true })
436
- } catch {
437
- return { moved: [], root: null }
438
- }
439
- const moved = []
440
- for (const target of targets) {
441
- const destination = await freeDestination(root, path.basename(target))
442
- if (destination === undefined) continue
443
- try {
444
- await fsp.rename(target, destination)
445
- moved.push(target)
446
- continue
447
- } catch {
448
- // A cross-volume rename fails; copy then drop the original.
449
- }
450
- try {
451
- await fsp.cp(target, destination, { recursive: true, force: false, errorOnExist: true })
452
- await fsp.rm(target, { recursive: true, force: true })
453
- moved.push(target)
454
- } catch {
455
- // Leave it: a path that cannot be retired is reported by the caller.
456
- }
457
- }
458
- return { moved, root: moved.length > 0 ? root : null }
459
- }
460
-
461
- /** Keeps two retires in the same millisecond out of one staging folder. */
462
- let retireCounter = 0
463
-
464
- /** The staging move alone, for callers that just want the paths out of the way. */
465
- async function moveToSessionTrash(targets) {
466
- return (await stageToTrash(targets)).moved
467
- }
468
-
469
- /**
470
- * Retire paths for good. The caller gets control back as soon as the paths are
471
- * out of their original location — a same-volume rename — and the Recycle Bin
472
- * move finishes in the background.
473
- *
474
- * That order is deliberate: the shell's recycle operation costs ~600 ms, which
475
- * is exactly the wait a delete should not have. If the background call fails, the
476
- * paths are still in `session-trash-<stamp>` and recoverable by hand; nothing is
477
- * ever unlinked.
478
- */
479
- async function retirePaths(targets) {
480
- if (targets.length === 0) return []
481
- const staged = await stageToTrash(targets)
482
- if (staged.root !== null) {
483
- // Fire and forget: never awaited, never allowed to reject into the caller.
484
- try {
485
- sendToRecycleBin([staged.root]).catch(() => {})
486
- } catch {
487
- // the staged copy stays where it is
488
- }
489
- }
490
- return staged.moved
491
- }
492
-
493
- /**
494
- * Remove paths outright. This is the branch behind the unchecked Recycle Bin
495
- * switch: the dialog says the delete is permanent in that state, so the files
496
- * must not linger anywhere. Every other path through this plugin retires to the
497
- * bin, and that difference is the whole point of the switch.
498
- *
499
- * @returns the paths that are gone afterwards.
500
- */
501
- function removeForever(targets) {
502
- const gone = []
503
- for (const target of targets) {
504
- if (!fs.existsSync(target)) continue
505
- try {
506
- fs.rmSync(target, { recursive: true, force: true })
507
- if (!fs.existsSync(target)) gone.push(target)
508
- } catch {
509
- // reported by the caller's own existence checks
510
- }
511
- }
512
- return gone
513
- }
514
- /**
515
- * Retire a list according to the switch: into the system trash (staged first,
516
- * then the shell takes it) or off the disk. Kept separate from the delete so the
517
- * choice itself can be tested without standing up a whole session.
518
- */
519
- async function retireTargets(targets, recycle) {
520
- return recycle ? retirePaths(targets) : removeForever(targets)
521
- }
522
- async function retireSessionDirs(sessionId) {
523
- return retirePaths(findSessionDirs(sessionId))
524
- }
525
-
526
- // Deleting the on-disk directory is not enough: projection caches keep a
527
- // per-session JSON row (`$DSH_HOME/storages/<store>/sessions/<id>.json`) that
528
- // would linger as a ghost — the sidebar list is directory-backed, so the row
529
- // can never be shown or deleted again (issue: "can't delete anymore"). Retire
530
- // the session's cache units together with its directories.
531
- function findSessionCaches(sessionId) {
532
- const storesRoot = path.join(dshHome(), 'storages')
533
- const found = []
534
- let stores
535
- try {
536
- stores = fs.readdirSync(storesRoot, { withFileTypes: true })
537
- } catch {
538
- return found
539
- }
540
- const names = idVariants(sessionId).map((variant) => `${variant}.json`)
541
- for (const store of stores) {
542
- if (!store.isDirectory()) continue
543
- const dir = path.join(storesRoot, store.name, 'sessions')
544
- let entries
545
- try {
546
- entries = fs.readdirSync(dir)
547
- } catch {
548
- continue
549
- }
550
- for (const entry of entries) {
551
- if (!names.includes(entry)) continue
552
- found.push(path.join(dir, entry))
553
- }
554
- }
555
- return found
556
- }
557
-
558
- async function retireSessionCaches(sessionId) {
559
- return retirePaths(findSessionCaches(sessionId))
560
- }
561
-
562
- // --- live state --------------------------------------------------------------
563
-
564
- // Stop a running agent before its session disappears: cancel the active turn
565
- // and wait, time-boxed, so a stuck driver never blocks the deletion.
566
- async function quiesceAgent(ctx, sessionId) {
567
- const agents = ctx.get('agents')
568
- if (!agents || typeof agents.get !== 'function') return false
569
- const agent = agents.get(sessionId)
570
- if (!agent) return false
571
- try {
572
- if (typeof agent.cancel === 'function') agent.cancel({ kind: 'user' })
573
- } catch {
574
- // agent may already be settling
575
- }
576
- if (typeof agent.whenIdle === 'function') {
577
- try {
578
- await Promise.race([agent.whenIdle(), new Promise((resolve) => setTimeout(resolve, 10000))])
579
- } catch {
580
- // proceed with deletion anyway
581
- }
582
- }
583
- return true
584
- }
585
-
586
- // Flush a live session, then detach its entered record so DSH emits
587
- // host/session-removed and the client list drops the row. The persistence
588
- // retirement started by session/disposed is awaited before the caller unlinks
589
- // anything, because its final drain could otherwise recreate the directory.
590
- async function flushAndDetach(ctx, sessionId) {
591
- const sessions = ctx.get('sessions')
592
- let flushed = false
593
- let detached = false
594
- if (sessions) {
595
- for (const variant of idVariants(sessionId)) {
596
- const live = typeof sessions.get === 'function' ? sessions.get(variant) : undefined
597
- if (!live) continue
598
- if (typeof sessions.flush === 'function') {
599
- try {
600
- await sessions.flush(live)
601
- flushed = true
602
- } catch {
603
- // the log is removed anyway
604
- }
605
- }
606
- try {
607
- const entered = sessions.store && typeof sessions.store.get === 'function' ? sessions.store.get(variant) : undefined
608
- if (entered && typeof entered.detach === 'function') {
609
- entered.detach()
610
- detached = true
611
- }
612
- } catch {
613
- // best effort: the directory removal below is the authority
614
- }
615
- }
616
- }
617
- const sp = ctx.get('sessionPersistence')
618
- try {
619
- const retirement = sp && sp.retirements && typeof sp.retirements.get === 'function' ? sp.retirements.get(sessionId) : undefined
620
- if (retirement && typeof retirement.then === 'function') await retirement
621
- } catch {
622
- // no retirement registry: nothing to wait for
623
- }
624
- return { flushed, detached }
625
- }
626
-
627
- // Probe the persistence write lease. Holding it proves no active writer is
628
- // around; it is released immediately. Detaching a live session releases its
629
- // lease asynchronously (session/disposed starts a persistence retirement), so
630
- // the probe is retried with a short backoff before the request is refused -
631
- // in practice the first click then succeeds without forcing anything.
632
- // The backoff is short (200ms x 12 = ~2.2s worst case) so a batch containing
633
- // live sessions stays responsive while the lease retirement lands.
634
- const BUSY_RETRY_ATTEMPTS = 12
635
- const BUSY_RETRY_DELAY_MS = 200
636
-
637
- function sleep(ms) {
638
- return new Promise((resolve) => setTimeout(resolve, ms))
639
- }
640
-
641
- async function assertNoActiveWriter(ctx, sessionId) {
642
- const sp = ctx.get('sessionPersistence')
643
- if (!sp || typeof sp.open !== 'function') return false
644
- for (let attempt = 1; attempt <= BUSY_RETRY_ATTEMPTS; attempt += 1) {
645
- let handle = null
646
- let busy = false
647
- try {
648
- handle = await sp.open(sessionId, 'write')
649
- } catch (error) {
650
- const message = String((error && error.message) || error)
651
- if (/own|busy|lock|hold|writer/i.test(message)) {
652
- busy = true
653
- } else {
654
- return false
655
- }
656
- } finally {
657
- try {
658
- if (handle && typeof handle.close === 'function') await handle.close()
659
- } catch {
660
- // lease release failure is harmless: the directory is removed next
661
- }
662
- }
663
- if (!busy) return true
664
- if (attempt < BUSY_RETRY_ATTEMPTS) await sleep(BUSY_RETRY_DELAY_MS)
665
- }
666
- throw new HttpError(409, 'busy', 'session is currently open in DSH')
667
- }
668
-
669
- // Bounded concurrency for batch deletes. Different sessions are independent
670
- // (agent quiesce, lease probe and directory sweep all key off the session id),
671
- // so the pipeline runs in parallel through a small pool. The one shared
672
- // mutation - workspace accounting - is serialized through withWorkspaceLock so
673
- // two deletions can never interleave on the same store.
674
- //
675
- // 6 is measured, not guessed: on 64 sessions of ~2MB the wall time was
676
- // 281ms at 4, 189ms at 6 and 142ms at 8 (the I/O parallelism saturates around
677
- // 8), so 6 keeps a ~33% gain over 4 while staying below the saturation knee
678
- // and limiting the number of simultaneous lease-probe loops.
679
- const BATCH_CONCURRENCY = 6
680
-
681
- let workspaceLock = Promise.resolve()
682
- function withWorkspaceLock(fn) {
683
- const run = workspaceLock.then(fn, fn)
684
- workspaceLock = run.then(() => undefined, () => undefined)
685
- return run
686
- }
687
-
688
- async function runWithConcurrency(items, limit, worker) {
689
- const results = new Array(items.length)
690
- let cursor = 0
691
- const runners = []
692
- for (let i = 0; i < Math.min(limit, items.length); i += 1) {
693
- runners.push((async () => {
694
- while (true) {
695
- const index = cursor
696
- cursor += 1
697
- if (index >= items.length) return
698
- results[index] = await worker(items[index], index)
699
- }
700
- })())
701
- }
702
- await Promise.all(runners)
703
- return results
704
- }
705
-
706
- async function detachFromWorkspace(ctx, sessionId) {
707
- const workspace = ctx.get('workspaceRegistry')
708
- if (!workspace) return false
709
- const variants = idVariants(sessionId)
710
- let touched = false
711
- try {
712
- if (typeof workspace.list === 'function') {
713
- for (const entry of workspace.list()) {
714
- if (!entry || !Array.isArray(entry.sessionIds)) continue
715
- if (!variants.some((variant) => entry.sessionIds.includes(variant))) continue
716
- try {
717
- await entry.detachSession(sessionId)
718
- touched = true
719
- } catch {
720
- // keep going: the header index cleanup below still applies
721
- }
722
- }
723
- }
724
- } catch {
725
- // registry unavailable
726
- }
727
- try {
728
- if (workspace.sessionPaths && typeof workspace.sessionPaths.delete === 'function') {
729
- for (const variant of variants) workspace.sessionPaths.delete(variant)
730
- }
731
- } catch {
732
- // private map absent on this version
733
- }
734
- try {
735
- if (workspace.headers && typeof workspace.headers.delete === 'function') {
736
- for (const variant of variants) workspace.headers.delete(variant)
737
- }
738
- } catch {
739
- // private map absent on this version
740
- }
741
- return touched
742
- }
743
-
744
- // --- core delete -------------------------------------------------------------
745
-
746
- async function deleteSession(ctx, sessionId, options) {
747
- if (!SESSION_ID_RE.test(sessionId)) {
748
- throw new HttpError(400, 'invalid', 'invalid session id')
749
- }
750
- // Undoable by default: only an explicit `recycle: false` sends the files to a
751
- // plain removal instead of the system trash.
752
- const recycle = options === undefined || options === null || options.recycle !== false
753
- // Subagent sessions are sessions of their own; the ones the caller ticked are
754
- // taken with their parent. Anything that is not a well-formed id is dropped
755
- // here, before it reaches the filesystem.
756
- const childSessionIds = options !== undefined && options !== null && Array.isArray(options.childSessionIds)
757
- ? options.childSessionIds
758
- .filter((id) => typeof id === 'string' && SESSION_ID_RE.test(id))
759
- .filter((id) => bareSessionId(id) !== bareSessionId(sessionId))
760
- : []
761
- const stopped = await quiesceAgent(ctx, sessionId)
762
- const { flushed, detached } = await flushAndDetach(ctx, sessionId)
763
- await assertNoActiveWriter(ctx, sessionId)
764
-
765
- // Retire the on-disk directories first, then the cache rows. With the Recycle
766
- // Bin switch on (the default) they are staged and the shell moves them to the
767
- // bin in the background; switched off, they are removed outright — that is what
768
- // the dialog promises in that state.
769
- const { removed, caches } = await retireSessionFiles(sessionId, recycle)
770
-
771
- const sp = ctx.get('sessionPersistence')
772
- if (sp && typeof sp.stat === 'function') {
773
- const after = await sp.stat(sessionId).catch(() => undefined)
774
- if (after) {
775
- throw new HttpError(500, 'verify-failed', 'session is still visible to the persistence service after deletion')
776
- }
777
- }
778
- const leftover = findSessionDirs(sessionId)
779
- if (leftover.length > 0) {
780
- throw new HttpError(500, 'verify-failed', 'session directories could not be fully removed')
781
- }
782
-
783
- const workspaceDetached = await withWorkspaceLock(() => detachFromWorkspace(ctx, sessionId))
784
- if (removed === 0 && !workspaceDetached && !flushed && !detached && caches === 0) {
785
- throw new HttpError(404, 'not-found', 'session not found')
786
- }
787
-
788
- // Children last, and one failure never takes the parent result down with it:
789
- // the parent is what the user clicked, so that click has to land.
790
- const children = []
791
- for (const childId of childSessionIds) {
792
- try {
793
- // A subagent can still be running while its parent is deleted. Removing the
794
- // log out from under it is what made the agent's next write fail with ENOENT,
795
- // so a child gets the same guard as the parent: stop it, flush it, and wait
796
- // for the write lease before a single byte moves.
797
- await quiesceAgent(ctx, childId)
798
- await flushAndDetach(ctx, childId)
799
- await assertNoActiveWriter(ctx, childId)
800
- const childFiles = await retireSessionFiles(childId, recycle)
801
- await withWorkspaceLock(() => detachFromWorkspace(ctx, childId))
802
- children.push({ id: childId, removed: childFiles.removed, caches: childFiles.caches })
803
- } catch (error) {
804
- // Never delete a child that could not be quieted: something is still writing
805
- // to it. Report it so the caller can try again once it settles.
806
- const busy = error instanceof HttpError && error.code === 'busy'
807
- children.push({
808
- id: childId,
809
- removed: 0,
810
- caches: 0,
811
- skipped: busy ? 'busy' : 'error',
812
- error: String((error && error.message) || error),
813
- })
814
- }
815
- }
816
-
817
- return {
818
- removed,
819
- caches,
820
- stopped,
821
- flushed,
822
- detached,
823
- workspaceDetached,
824
- children,
825
- }
826
- }
827
-
828
- /**
829
- * Take one session off the disk: its directories and its cache rows, then any
830
- * directory the drain recreated. Shared by the parent and every child, so a
831
- * subagent is retired exactly like the conversation the user clicked.
832
- *
833
- * @returns how many paths went away, and how many cache rows are now gone.
834
- */
835
- async function retireSessionFiles(sessionId, recycle) {
836
- const cacheFiles = findSessionCaches(sessionId)
837
- const targets = [...findSessionDirs(sessionId), ...cacheFiles]
838
- let gone = await retireTargets(targets, recycle)
839
- await new Promise((resolve) => setImmediate(resolve))
840
- gone = gone.concat(await retireTargets(findSessionDirs(sessionId), recycle))
841
- return { removed: gone.length, caches: cacheFiles.filter((file) => !fs.existsSync(file)).length }
842
- }
843
-
844
- // --- artifacts: what a session touched, and quarantining it -----------------
845
- //
846
- // "Produced files" is derived from the durable session log alone: the log is the
847
- // only record that outlives a closed Session (the host's own observation state
848
- // lives in a plugin-local WeakMap and dies with the process, and the
849
- // `workspace/changes` summaries live in a temporary directory that disposal
850
- // removes). Classification rests on one invariant of the default
851
- // fs-observation-policy: `write` may not overwrite a file that was not read
852
- // first, and `edit` requires a prior read. So a write whose path has no earlier
853
- // successful read CREATED the file; anything else already existed.
854
- //
855
- // Nothing here deletes. Files are moved into a timestamped quarantine directory
856
- // under $DSH_HOME, keeping their path relative to the session's working
857
- // directory, so a wrong call is recoverable.
858
-
859
- const QUARANTINE_PREFIX = 'purge-quarantine'
860
- const MAX_LISTED = 500
861
- /**
862
- * How many distinct paths one scan will resolve. Every path costs a realpath,
863
- * and a session that walked a large tree can name tens of thousands of them;
864
- * the dialog would sit on "scanning" for as long as they take. Past this the
865
- * plan reports `truncated`, which the dialog already surfaces.
866
- */
867
- const MAX_SCANNED = 2000
868
- /** How many path resolutions run at once: enough to hide the threadpool round trip, few enough to stay polite. */
869
- const RESOLVE_CONCURRENCY = 16
870
- /** How many directories the folder picker lists before saying there are more. */
871
- const MAX_BROWSE_ENTRIES = 500
872
- /** How long the OS chooser may stay open before the request gives up on it. */
873
- const PICK_TIMEOUT_MS = 5 * 60 * 1000
874
- /** How long a shell helper (the recycle-bin script) may run before giving up. */
875
- const SHELL_TIMEOUT_MS = 5 * 60 * 1000
876
-
877
- /** Run a program and collect its output, leaving the meaning of the exit to the caller. */
878
- function runExecutable(program, args, timeoutMs) {
879
- return new Promise((resolve, reject) => {
880
- const child = spawn(program, args, { windowsHide: true })
881
- let out = ''
882
- let err = ''
883
- let settled = false
884
- const finish = (fn, value) => {
885
- if (settled) return
886
- settled = true
887
- clearTimeout(timer)
888
- fn(value)
889
- }
890
- const timer = setTimeout(() => {
891
- try { child.kill() } catch { /* already gone */ }
892
- finish(reject, new HttpError(504, 'timeout', '等待系统对话框超时'))
893
- }, timeoutMs)
894
-
895
- child.stdout.on('data', (chunk) => { out += chunk.toString('utf8') })
896
- child.stderr.on('data', (chunk) => { err += chunk.toString('utf8') })
897
- child.on('error', (error) => {
898
- finish(reject, new HttpError(500, 'spawn', `无法启动 ${path.basename(program)}:${String((error && error.message) || error)}`))
899
- })
900
- child.on('close', (code) => finish(resolve, { code, stdout: out, stderr: err }))
901
- })
902
- }
903
-
904
- /** Argument keys carrying the target path, per writing tool. */
905
- const WRITE_TOOL_PATHS = {
906
- write: ['file_path', 'path'],
907
- edit: ['file_path', 'path'],
908
- str_replace_editor: ['path', 'file_path'],
909
- create_file: ['file_path', 'path'],
910
- }
911
-
912
- /** Argument keys carrying the target path, per reading tool. */
913
- const READ_TOOL_PATHS = {
914
- read: ['file_path', 'path'],
915
- read_file: ['file_path', 'path'],
916
- }
917
-
918
- /**
919
- * Resolve the target path one tool call names.
920
- * @param name - tool name.
921
- * @param argumentsJson - the model's raw argument JSON.
922
- * @param cwd - the session's recorded working directory, for relative paths.
923
- * @returns the absolute path and whether the tool writes, or undefined.
924
- */
925
- function toolTarget(name, argumentsJson, cwd) {
926
- const writes = Object.prototype.hasOwnProperty.call(WRITE_TOOL_PATHS, name)
927
- const keys = writes ? WRITE_TOOL_PATHS[name] : READ_TOOL_PATHS[name]
928
- if (keys === undefined) return undefined
929
- let args
930
- try {
931
- args = JSON.parse(typeof argumentsJson === 'string' ? argumentsJson : '')
932
- } catch {
933
- return undefined
934
- }
935
- if (args === null || typeof args !== 'object' || Array.isArray(args)) return undefined
936
- const raw = keys.map((key) => args[key]).find((value) => typeof value === 'string' && value.trim() !== '')
937
- if (raw === undefined) return undefined
938
- let absolute
939
- if (path.isAbsolute(raw)) absolute = raw
940
- else if (cwd === undefined) return undefined
941
- else absolute = path.resolve(cwd, raw)
942
- return { path: absolute, writes }
943
- }
944
-
945
- /** Read a stored session's events through the persistence seam. */
946
- async function readSessionEvents(ctx, sessionId) {
947
- const sp = ctx.get('sessionPersistence')
948
- if (!sp || typeof sp.open !== 'function') {
949
- return { events: [], warning: '持久化服务不可用,无法读取会话日志' }
950
- }
951
- let handle = null
952
- try {
953
- handle = await sp.open(sessionId, 'read')
954
- const result = await handle.read()
955
- const events = Array.isArray(result && result.events) ? result.events : []
956
- return { events, warning: undefined }
957
- } catch (error) {
958
- return { events: [], warning: `读取会话日志失败:${String((error && error.message) || error)}` }
959
- } finally {
960
- try {
961
- if (handle && typeof handle.close === 'function') await handle.close()
962
- } catch {
963
- // a close failure must not change the plan
964
- }
965
- }
966
- }
967
-
968
- /**
969
- * Identity of one path for "have we seen this file before?" purposes. The real
970
- * path when it resolves, so a symlink alias and its target count as the same
971
- * file; otherwise a case-folded resolved path on Windows, whose filesystem does
972
- * not distinguish `Foo.md` from `foo.md`. Comparing spellings instead would let
973
- * a write through an alias look like a creation.
974
- * @param absolute - the path a tool call named.
975
- * @param cache - optional per-scan memo; without it the resolution cost scales
976
- * with log length rather than with the number of distinct files.
977
- * @returns a stable key for the file, not for the spelling.
978
- */
979
- async function identityKey(absolute, cache) {
980
- if (cache !== undefined) {
981
- const hit = cache.get(absolute)
982
- if (hit !== undefined) return hit
983
- }
984
- let key
985
- try {
986
- key = await realpathNative(absolute)
987
- } catch {
988
- const resolved = path.resolve(absolute)
989
- key = process.platform === 'win32' ? resolved.toLowerCase() : resolved
990
- }
991
- if (cache !== undefined) cache.set(absolute, key)
992
- return key
993
- }
994
-
995
- /**
996
- * Every path this session's writing tools touched, split by whether the session
997
- * created it or found it already there.
998
- * @param events - stored session events, in order.
999
- * @param cwd - the session's recorded working directory.
1000
- * @param cache - optional per-scan memo for path resolution, shared across calls.
1001
- * @returns `{ created, modified }`, keyed by file identity, each row `{ path, identity, ops }`.
1002
- */
1003
- async function collectSessionPaths(events, cwd, cache) {
1004
- const pending = new Map()
1005
- const read = new Set()
1006
- const created = new Map()
1007
- const modified = new Map()
1008
- const memo = cache !== undefined ? cache : new Map()
1009
-
1010
- // Resolve every distinct path the log names first, together. A long session
1011
- // names the same handful of files thousands of times, so awaiting per call
1012
- // would buy one threadpool round trip per mention; this buys one per file.
1013
- const named = new Set()
1014
- let overflow = false
1015
- for (const event of events) {
1016
- const data = event && event.data
1017
- if (!data || typeof data !== 'object' || event.type !== 'tool/call') continue
1018
- const target = toolTarget(typeof data.name === 'string' ? data.name : '', data.arguments, cwd)
1019
- if (target === undefined) continue
1020
- if (named.size >= MAX_SCANNED && !named.has(target.path)) {
1021
- overflow = true
1022
- break
1023
- }
1024
- named.add(target.path)
1025
- }
1026
- await runWithConcurrency([...named], RESOLVE_CONCURRENCY, async (absolute) => {
1027
- await identityKey(absolute, memo)
1028
- })
1029
-
1030
- const commit = (call) => {
1031
- // A file the session created and later edited stays "created": one identity
1032
- // must never sit in both buckets, or a scope=all run would target it twice
1033
- // and report a spurious failure for the second attempt.
1034
- const alreadyCreated = created.get(call.identity)
1035
- if (alreadyCreated !== undefined) {
1036
- alreadyCreated.ops += 1
1037
- return
1038
- }
1039
- const bucket = call.existedBefore ? modified : created
1040
- const prior = bucket.get(call.identity)
1041
- if (prior !== undefined) prior.ops += 1
1042
- else bucket.set(call.identity, { path: call.path, identity: call.identity, ops: 1 })
1043
- }
1044
-
1045
- for (const event of events) {
1046
- const data = event && event.data
1047
- if (!data || typeof data !== 'object') continue
1048
-
1049
- if (event.type === 'tool/call') {
1050
- const name = typeof data.name === 'string' ? data.name : ''
1051
- const target = toolTarget(name, data.arguments, cwd)
1052
- // Existence is decided at call time, against the reads that already
1053
- // succeeded - the policy's own ordering - and on identity, so an alias of
1054
- // a file the session read is still an edit.
1055
- if (target !== undefined) {
1056
- const identity = await identityKey(target.path, memo)
1057
- pending.set(data.callId, {
1058
- path: target.path,
1059
- identity,
1060
- writes: target.writes,
1061
- existedBefore: read.has(identity),
1062
- })
1063
- }
1064
- continue
1065
- }
1066
-
1067
- if (event.type !== 'tool/result') continue
1068
- const message = data.message
1069
- const callId = message && typeof message.toolCallId === 'string' ? message.toolCallId : undefined
1070
- if (callId === undefined) continue
1071
- const call = pending.get(callId)
1072
- if (call === undefined) continue
1073
- pending.delete(callId)
1074
- if (data.error !== undefined || (message && message.isError === true)) continue
1075
- if (call.writes) commit(call)
1076
- else read.add(call.identity)
1077
- }
1078
-
1079
- return { named: named.size, overflow, created, modified }
1080
- }
1081
-
1082
- /**
1083
- * Whether `child` is strictly inside `parent`, comparing real paths. Folded on
1084
- * Windows, where the filesystem ignores case: a realpath does not normalise the
1085
- * case of a prefix that still matches a differently-spelled spelling.
1086
- */
1087
- function insidePath(parent, child) {
1088
- if (parent === child) return false
1089
- const fold = (value) => (process.platform === 'win32' ? value.toLowerCase() : value)
1090
- const base = fold(parent)
1091
- const prefix = base.endsWith(path.sep) ? base : base + path.sep
1092
- return fold(child).startsWith(prefix)
1093
- }
1094
-
1095
- /**
1096
- * Is this directory inside a git working tree? A `.git` entry marks the root —
1097
- * a directory in a normal clone, a file in a worktree or a submodule.
1098
- *
1099
- * The walk memoises per directory: one plan can span hundreds of files that share
1100
- * a handful of folders, and each miss would otherwise stat every level again.
1101
- */
1102
- async function isInsideGitRepo(directory, cache) {
1103
- let current = path.resolve(directory)
1104
- const walked = []
1105
- for (;;) {
1106
- if (cache.has(current)) {
1107
- const verdict = cache.get(current)
1108
- for (const dir of walked) cache.set(dir, verdict)
1109
- return verdict
1110
- }
1111
- walked.push(current)
1112
- try {
1113
- const marker = await fsp.stat(path.join(current, '.git'))
1114
- if (marker.isDirectory() || marker.isFile()) {
1115
- for (const dir of walked) cache.set(dir, true)
1116
- return true
1117
- }
1118
- } catch {
1119
- // no .git here; keep walking up
1120
- }
1121
- const parent = path.dirname(current)
1122
- if (parent === current) {
1123
- for (const dir of walked) cache.set(dir, false)
1124
- return false
1125
- }
1126
- current = parent
1127
- }
1128
- }
1129
-
1130
- /**
1131
- * Keep only the paths that may actually be moved: an existing regular file whose
1132
- * real path is strictly inside the session's working directory and outside the
1133
- * DSH home. Every rejection carries its reason.
1134
- * @param rows - candidate rows `{ path, ops }`.
1135
- * @param cwd - the session's recorded working directory.
1136
- * @param home - resolved DSH home.
1137
- * @param options - `{ skipGit }`: also refuse files inside a git working tree.
1138
- * @returns `{ allowed, refused }`.
1139
- */
1140
- async function classifyPaths(rows, cwd, home, options) {
1141
- const allowed = []
1142
- const refused = []
1143
- const skipGit = options !== undefined && options !== null && options.skipGit === true
1144
- const gitCache = new Map()
1145
- const list = [...rows.values()]
1146
- if (cwd === undefined) {
1147
- for (const row of list) refused.push({ path: row.path, reason: '会话未记录工作目录,无法安全定位' })
1148
- return { allowed, refused }
1149
- }
1150
- let realCwd
1151
- try {
1152
- realCwd = await fsp.realpath(cwd)
1153
- } catch {
1154
- for (const row of list) refused.push({ path: row.path, reason: '会话工作目录已不存在,无法校验归属' })
1155
- return { allowed, refused }
1156
- }
1157
- let realHome = home
1158
- try {
1159
- realHome = await fsp.realpath(home)
1160
- } catch {
1161
- // an absent home cannot contain anything that exists
1162
- }
1163
- // Resolve each row's stat and real path together rather than one after another:
1164
- // a long session can list hundreds of files, and awaiting them serially turns
1165
- // one threadpool round trip into hundreds. `runWithConcurrency` keeps the order.
1166
- const verdicts = await runWithConcurrency(list, RESOLVE_CONCURRENCY, async (row) => {
1167
- let info
1168
- try {
1169
- info = await fsp.stat(row.path)
1170
- } catch {
1171
- return { refuse: { path: row.path, reason: '文件已不存在' } }
1172
- }
1173
- if (!info.isFile()) return { refuse: { path: row.path, reason: '不是普通文件,已跳过' } }
1174
- let real
1175
- try {
1176
- real = await fsp.realpath(row.path)
1177
- } catch {
1178
- return { refuse: { path: row.path, reason: '无法解析真实路径,已跳过' } }
1179
- }
1180
- if (!insidePath(realCwd, real)) {
1181
- return { refuse: { path: row.path, reason: '不在该对话的工作目录内,已跳过' } }
1182
- }
1183
- if (insidePath(realHome, real)) {
1184
- return { refuse: { path: row.path, reason: '位于 DSH 数据目录内,已跳过' } }
1185
- }
1186
- if (skipGit && await isInsideGitRepo(path.dirname(real), gitCache)) {
1187
- return { refuse: { path: row.path, reason: '位于 git 仓库内,已跳过' } }
1188
- }
1189
- return { allow: { path: real, displayPath: row.path, ops: row.ops, bytes: info.size, mtime: info.mtimeMs } }
1190
- })
1191
- for (const verdict of verdicts) {
1192
- if (verdict.allow !== undefined) allowed.push(verdict.allow)
1193
- else refused.push(verdict.refuse)
1194
- }
1195
- return { allowed, refused }
1196
- }
1197
-
1198
- /**
1199
- * Build the artifact plan for one session.
1200
- * @param ctx - host plugin context.
1201
- * @param sessionId - validated session id.
1202
- * @returns `{ cwd, created, modified, refused, truncated, warnings }`.
1203
- */
1204
- async function planArtifacts(ctx, sessionId, cache, options) {
1205
- const home = dshHome()
1206
- const warnings = []
1207
- const sp = ctx.get('sessionPersistence')
1208
- let cwd
1209
- if (sp && typeof sp.stat === 'function') {
1210
- try {
1211
- const snapshot = await sp.stat(sessionId)
1212
- let header = null
1213
- if (snapshot !== null && typeof snapshot === 'object') {
1214
- header = snapshot.header !== null && typeof snapshot.header === 'object' ? snapshot.header : snapshot
1215
- }
1216
- if (header && typeof header.cwd === 'string' && header.cwd !== '') cwd = header.cwd
1217
- } catch (error) {
1218
- warnings.push(`未找到该会话的存储记录:${String((error && error.message) || error)}`)
1219
- }
1220
- }
1221
- const { events, warning } = await readSessionEvents(ctx, sessionId)
1222
- if (warning !== undefined) warnings.push(warning)
1
+ // dsh-delete-session - host half.
2
+ //
3
+ // Loopback-only HTTP routes serve the client half:
4
+ //
5
+ // POST /dsh-delete-session/delete { sessionId }
6
+ //
7
+ // Deletion pipeline, kept consistent with the live DSH services so in-memory
8
+ // state and on-disk units cannot disagree after the request returns:
9
+ //
10
+ // 1. stop a running agent (cancel + time-boxed quiescence) when one exists;
11
+ // 2. flush and detach the live session so its async dispose cannot rewrite
12
+ // the log directory after we remove it, and wait for the persistence
13
+ // retirement that session/disposed starts;
14
+ // 3. take the persistence write lease briefly: a busy lease means the
15
+ // session is still open in DSH, so the request is refused with 409
16
+ // instead of racing the active writer;
17
+ // 4. remove every on-disk session directory (raw id and session- prefix);
18
+ // 5. verify through the persistence service and a directory re-scan;
19
+ // 6. detach the session from workspace accounting so the sidebar drops the
20
+ // row instead of re-grouping an orphan under "Ungrouped".
21
+ //
22
+ // The plugin imports nothing from the DSH SDK: every service is resolved
23
+ // through the cordis context at call time, so the module loads on any profile
24
+ // and degrades to the filesystem path when a service is absent.
25
+ import { spawn } from 'node:child_process'
26
+ import fs from 'node:fs'
27
+ import os from 'node:os'
28
+ import path from 'node:path'
29
+ import { promisify } from 'node:util'
30
+
31
+ /** The asynchronous face of `fs`, used wherever a blocking call could stall the server. */
32
+ const fsp = fs.promises
33
+ /** The same underlying call as `fs.realpathSync.native`, just not blocking. */
34
+ const realpathNative = promisify(fs.realpath.native)
35
+
36
+ export const name = 'dsh-delete-session'
37
+
38
+ const ROUTE_PREFIX = '/dsh-delete-session'
39
+ // A session id is an OPAQUE string to DSH: the host's own schema is
40
+ // `z.string().min(1)`, and a named session created in the GUI (`bili-whale`,
41
+ // stored as ~/.dsh/storages/<profile>/sessions/bili-whale.json) is exactly as
42
+ // real as a UUID one. A UUID-only test rejected those with a 400 - the panel
43
+ // then answered "状态加载失败" for a session that plainly exists, and a session
44
+ // list filtered by it hid them. The character class still refuses everything
45
+ // that could leave a path or a URL: `/`, `\`, `..` (the first character must be
46
+ // alphanumeric, so a leading dot is already out), whitespace and control
47
+ // characters.
48
+ const SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/
49
+ const MAX_BATCH = 100
50
+
51
+ class HttpError extends Error {
52
+ constructor(status, code, message) {
53
+ super(message)
54
+ this.status = status
55
+ this.code = code
56
+ }
57
+ }
58
+
59
+ // --- paths -------------------------------------------------------------------
60
+
61
+ function dshHome() {
62
+ return process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
63
+ }
64
+
65
+ function sessionsRoot() {
66
+ return path.join(dshHome(), 'sessions')
67
+ }
68
+
69
+ // A session id travels in two spellings: the raw uuid and `session-<uuid>`.
70
+ // The on-disk JSONL backend uses the prefixed form for the directory name,
71
+ // while workspace and projection rows may carry either. Clean both.
72
+ function idVariants(sessionId) {
73
+ const out = new Set([sessionId])
74
+ if (sessionId.startsWith('session-')) out.add(sessionId.slice('session-'.length))
75
+ else out.add(`session-${sessionId}`)
76
+ return [...out]
77
+ }
78
+ /** The bare uuid, for comparing ids that may or may not carry the prefix. */
79
+ function bareSessionId(sessionId) {
80
+ return sessionId.startsWith('session-') ? sessionId.slice('session-'.length) : sessionId
81
+ }
82
+
83
+ /**
84
+ * Every session header the host knows about, or `[]` when no service can list
85
+ * them. `sessionQuery` merges live and persisted sessions and carries
86
+ * `parentSession`, so the parent/child map never has to be decoded out of the
87
+ * zstd logs.
88
+ */
89
+ async function listSessionHeaders(ctx) {
90
+ try {
91
+ const query = ctx.get('sessionQuery')
92
+ if (query && typeof query.listSessions === 'function') {
93
+ const records = await query.listSessions()
94
+ const headers = records
95
+ .map((record) => record && record.header)
96
+ .filter((header) => header && typeof header.id === 'string')
97
+ if (headers.length > 0) return headers
98
+ }
99
+ } catch {
100
+ // fall through to the persistence service
101
+ }
102
+ try {
103
+ const persistence = ctx.get('sessionPersistence')
104
+ if (persistence && typeof persistence.list === 'function') {
105
+ const snapshots = await persistence.list({})
106
+ return snapshots
107
+ .map((snapshot) => snapshot && snapshot.header)
108
+ .filter((header) => header && typeof header.id === 'string')
109
+ }
110
+ } catch {
111
+ // no service can list sessions on this host
112
+ }
113
+ return []
114
+ }
115
+
116
+ /**
117
+ * Every descendant of one session, breadth first. A subagent is a session of
118
+ * its own — its own directory and its own log — linked only by `parentSession`,
119
+ * so a delete that ignores the link leaves orphans behind.
120
+ *
121
+ * @param headers - the host session headers.
122
+ * @param sessionId - the session being deleted.
123
+ * @returns descendant headers, parents before their own children.
124
+ */
125
+ function collectDescendants(headers, sessionId) {
126
+ const byParent = new Map()
127
+ for (const header of headers) {
128
+ if (typeof header.parentSession !== 'string') continue
129
+ // Only subagents belong to a parent. A fork records where it branched from,
130
+ // but it is a conversation of its own and the user can open it like any other:
131
+ // sweeping those up deletes work nobody asked to delete.
132
+ if (header.origin !== 'subagent') continue
133
+ const key = bareSessionId(header.parentSession)
134
+ const list = byParent.get(key)
135
+ if (list === undefined) byParent.set(key, [header])
136
+ else list.push(header)
137
+ }
138
+ const found = []
139
+ const seen = new Set([bareSessionId(sessionId)])
140
+ const queue = [bareSessionId(sessionId)]
141
+ while (queue.length > 0) {
142
+ const current = queue.shift()
143
+ for (const child of byParent.get(current) ?? []) {
144
+ const key = bareSessionId(child.id)
145
+ if (seen.has(key)) continue
146
+ seen.add(key)
147
+ found.push(child)
148
+ queue.push(key)
149
+ }
150
+ }
151
+ return found
152
+ }
153
+
154
+ /**
155
+ * Sessions whose parent no longer exists. Deleting a parent used to leave these
156
+ * on disk, and the sidebar cannot show the ones that never joined a workspace.
157
+ */
158
+ function collectOrphans(headers) {
159
+ const present = new Set(headers.map((entry) => bareSessionId(entry.id)))
160
+ // Same rule as the descendant walk: a fork whose source is gone is still a
161
+ // conversation of its own, not an abandoned child.
162
+ return headers.filter((entry) => entry.origin === 'subagent'
163
+ && typeof entry.parentSession === 'string'
164
+ && !present.has(bareSessionId(entry.parentSession)))
165
+ }
166
+
167
+ /**
168
+ * The child list the dialog shows: identity, nesting depth and the project the
169
+ * subagent ran in, so the names are recognisable before anything is ticked.
170
+ */
171
+ function describeChildren(headers, sessionId) {
172
+ const byBare = new Map(headers.map((entry) => [bareSessionId(entry.id), entry]))
173
+ return collectDescendants(headers, sessionId).map((entry) => {
174
+ let depth = 1
175
+ let cursor = entry
176
+ while (typeof cursor.parentSession === 'string') {
177
+ const parent = byBare.get(bareSessionId(cursor.parentSession))
178
+ if (parent === undefined || bareSessionId(parent.id) === bareSessionId(sessionId)) break
179
+ depth += 1
180
+ cursor = parent
181
+ }
182
+ return {
183
+ id: entry.id,
184
+ depth,
185
+ cwd: typeof entry.cwd === 'string' ? entry.cwd : undefined,
186
+ }
187
+ })
188
+ }
189
+
190
+ /**
191
+ * The children the caller asked to delete, narrowed to real descendants. A
192
+ * stale or unrelated id is dropped instead of failing the delete: the parent is
193
+ * the session the user clicked, and that click must still land.
194
+ *
195
+ * @returns the descendants' own ids, in the order they were asked for.
196
+ */
197
+ function selectChildDeletes(headers, sessionId, requested) {
198
+ if (!Array.isArray(requested) || requested.length === 0) return []
199
+ const descendants = new Map()
200
+ for (const entry of collectDescendants(headers, sessionId)) {
201
+ descendants.set(bareSessionId(entry.id), entry.id)
202
+ }
203
+ const picked = []
204
+ for (const id of requested) {
205
+ if (typeof id !== 'string' || id === '') continue
206
+ const hit = descendants.get(bareSessionId(id))
207
+ if (hit !== undefined && !picked.includes(hit)) picked.push(hit)
208
+ }
209
+ return picked
210
+ }
211
+
212
+ // Scan every workspace directory under $DSH_HOME/sessions for the session's
213
+ // directories, so the workspace-path encoding never has to be re-derived here.
214
+ function findSessionDirs(sessionId) {
215
+ const root = sessionsRoot()
216
+ let entries
217
+ try {
218
+ entries = fs.readdirSync(root, { withFileTypes: true })
219
+ } catch {
220
+ return []
221
+ }
222
+ const variants = idVariants(sessionId)
223
+ const found = []
224
+ for (const entry of entries) {
225
+ if (!entry.isDirectory()) continue
226
+ for (const variant of variants) {
227
+ const candidate = path.join(root, entry.name, variant)
228
+ try {
229
+ if (fs.statSync(candidate).isDirectory() && !found.includes(candidate)) found.push(candidate)
230
+ } catch {
231
+ // keep scanning
232
+ }
233
+ }
234
+ }
235
+ return found
236
+ }
237
+
238
+ /**
239
+ * The C# behind the cached recycle helper. One process handles every path of a
240
+ * delete (the session directory and its cache rows), because each PowerShell
241
+ * start costs the better part of a second and a delete used to pay it twice.
242
+ */
243
+ const RECYCLE_CSHARP = `using System;
244
+ using System.IO;
245
+ using Microsoft.VisualBasic.FileIO;
246
+
247
+ public static class Program {
248
+ public static int Main(string[] args) {
249
+ int done = 0;
250
+ foreach (string target in args) {
251
+ try {
252
+ if (Directory.Exists(target)) {
253
+ FileSystem.DeleteDirectory(target, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
254
+ } else if (File.Exists(target)) {
255
+ FileSystem.DeleteFile(target, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
256
+ }
257
+ done++;
258
+ } catch {
259
+ // leave it: the caller verifies the path is gone
260
+ }
261
+ }
262
+ return done == args.Length ? 0 : 1;
263
+ }
264
+ }`
265
+
266
+ /** Bump when `RECYCLE_CSHARP` changes, so a cached build is not reused. */
267
+ const RECYCLE_EXE_VERSION = 1
268
+ const RECYCLE_TIMEOUT_MS = 60 * 1000
269
+
270
+ /** The C# compiler that ships with .NET Framework, if this machine has it. */
271
+ function findCsc() {
272
+ const windir = process.env.WINDIR || 'C:\\Windows'
273
+ for (const flavor of ['Framework64', 'Framework']) {
274
+ const candidate = path.join(windir, 'Microsoft.NET', flavor, 'v4.0.30319', 'csc.exe')
275
+ try {
276
+ if (fs.statSync(candidate).isFile()) return candidate
277
+ } catch {
278
+ // try the next flavour
279
+ }
280
+ }
281
+ return null
282
+ }
283
+
284
+ /** Compile the recycle helper once into the DSH cache; null when it cannot. */
285
+ async function ensureRecycleExe() {
286
+ if (process.platform !== 'win32') return null
287
+ const dir = path.join(dshHome(), 'cache', 'dsh-delete-session', `v${RECYCLE_EXE_VERSION}`)
288
+ const exe = path.join(dir, 'dsh-recycle.exe')
289
+ if (await pathExists(exe)) return exe
290
+ const csc = findCsc()
291
+ if (csc === null) return null
292
+ try {
293
+ await fsp.mkdir(dir, { recursive: true })
294
+ const source = path.join(dir, 'recycle.cs')
295
+ await fsp.writeFile(source, RECYCLE_CSHARP, 'utf8')
296
+ const built = await runExecutable(csc, ['-nologo', '-target:exe', `-out:${exe}`, '-r:System.dll', '-r:Microsoft.VisualBasic.dll', source], PICK_COMPILE_TIMEOUT_MS)
297
+ try { await fsp.rm(source, { force: true }) } catch { /* best effort */ }
298
+ if (built.code === 0) {
299
+ if (await pathExists(exe)) return exe
300
+ }
301
+ } catch {
302
+ // fall through to the PowerShell path
303
+ }
304
+ return null
305
+ }
306
+
307
+ /**
308
+ * The command that hands paths to the platform trash.
309
+ *
310
+ * Windows is done in-process (see `sendToRecycleBin`); macOS has no trash command
311
+ * of its own, so Finder performs the delete, and Linux delegates to `gio trash`,
312
+ * which ships with GLib on every mainstream desktop. Kept separate from running
313
+ * it so the shape can be tested on a machine that has neither.
314
+ */
315
+ /**
316
+ * Compile the helper executables while nothing is waiting for them. The first
317
+ * pick or delete otherwise pays for `csc` (0.5-1.7 s); by the time the user
318
+ * clicks, the cache is already there.
319
+ *
320
+ * Deliberately fire-and-forget and never fatal: a machine without `csc` keeps
321
+ * the PowerShell fallbacks, and a failure here must not stop the plugin loading.
322
+ */
323
+ function warmCompiledHelpers() {
324
+ if (process.platform !== 'win32') return
325
+ const warm = async () => {
326
+ try { await ensureRecycleExe() } catch { /* the fallback covers it */ }
327
+ }
328
+ void warm()
329
+ }
330
+ function trashCommandFor(platform, targets) {
331
+ if (platform === 'darwin') {
332
+ // One -e per path: AppleScript has no list form for this, and a failure on one
333
+ // path must not stop the rest.
334
+ return {
335
+ program: 'osascript',
336
+ args: targets.flatMap((target) => [
337
+ '-e',
338
+ `tell application "Finder" to delete (POSIX file "${target.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}")`,
339
+ ]),
340
+ }
341
+ }
342
+ return { program: 'gio', args: ['trash', ...targets] }
343
+ }
344
+
345
+ /**
346
+ * Run the platform trash command. Returns false when the command is missing
347
+ * (`gio` on a bare container, a denied Finder automation prompt) so the caller
348
+ * keeps the staged copy instead of pretending the delete happened.
349
+ */
350
+ async function trashWithSystem(targets, platform) {
351
+ const command = trashCommandFor(platform, targets)
352
+ try {
353
+ const run = await runExecutable(command.program, command.args, RECYCLE_TIMEOUT_MS)
354
+ return run.code === 0
355
+ } catch {
356
+ return false
357
+ }
358
+ }
359
+
360
+ /**
361
+ * Send paths to the Windows Recycle Bin.
362
+ *
363
+ * A delete has to be undoable, and the Recycle Bin is the undo the user already
364
+ * knows. Node has no API for it, and a Node process cannot synthesize the
365
+ * `$I`/`$R` pair the Shell owns, so one PowerShell does the work through
366
+ * `Microsoft.VisualBasic.FileIO.FileSystem` — the supported managed wrapper of
367
+ * "delete with undo". The script prints one verdict per path, so a partial
368
+ * failure is reported instead of being assumed away.
369
+ *
370
+ * @returns `true` only when every path actually left its original location.
371
+ */
372
+ async function sendToRecycleBin(targets) {
373
+ if (targets.length === 0) return true
374
+ // macOS and Linux have their own trash; Windows is handled below in-process.
375
+ if (process.platform !== 'win32') return trashWithSystem(targets, process.platform)
376
+
377
+ // The compiled helper answers in ~100 ms where one PowerShell start costs the
378
+ // better part of a second, and it takes every path of a delete at once.
379
+ const exe = await ensureRecycleExe()
380
+ if (exe !== null) {
381
+ try {
382
+ const run = await runExecutable(exe, targets, RECYCLE_TIMEOUT_MS)
383
+ return run.code === 0
384
+ } catch {
385
+ return false
386
+ }
387
+ }
388
+
389
+ const list = targets.map((target) => `'${target.replace(/'/g, "''")}'`).join(', ')
390
+ const script = [
391
+ 'Add-Type -AssemblyName Microsoft.VisualBasic',
392
+ `$targets = @(${list})`,
393
+ 'foreach ($target in $targets) {',
394
+ ' try {',
395
+ ' if (Test-Path -LiteralPath $target -PathType Container) {',
396
+ ' [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($target,',
397
+ ' [Microsoft.VisualBasic.FileIO.UIOption]::OnlyErrorDialogs,',
398
+ ' [Microsoft.VisualBasic.FileIO.RecycleOption]::SendToRecycleBin)',
399
+ ' } elseif (Test-Path -LiteralPath $target) {',
400
+ ' [Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($target,',
401
+ ' [Microsoft.VisualBasic.FileIO.UIOption]::OnlyErrorDialogs,',
402
+ ' [Microsoft.VisualBasic.FileIO.RecycleOption]::SendToRecycleBin)',
403
+ ' }',
404
+ ' [Console]::Out.WriteLine(\'OK\')',
405
+ ' } catch {',
406
+ ' [Console]::Out.WriteLine(\'FAIL\')',
407
+ ' }',
408
+ '}',
409
+ ].join('\r\n')
410
+
411
+ const scriptPath = path.join(os.tmpdir(), `dsh-delete-session-bin-${process.pid}-${Date.now()}.ps1`)
412
+ const bytes = Buffer.concat([Buffer.from([0xEF, 0xBB, 0xBF]), Buffer.from(script, 'utf8')])
413
+ let output
414
+ try {
415
+ await fsp.writeFile(scriptPath, bytes)
416
+ output = await runPowershell(
417
+ ['-NoProfile', '-STA', '-ExecutionPolicy', 'Bypass', '-File', scriptPath],
418
+ SHELL_TIMEOUT_MS,
419
+ )
420
+ } catch {
421
+ return false
422
+ } finally {
423
+ try { await fsp.rm(scriptPath, { force: true }) } catch { /* best effort */ }
424
+ }
425
+ const ok = output.split(/\r?\n/).filter((line) => line.trim() === 'OK').length
426
+ return ok === targets.length
427
+ }
428
+
429
+ /**
430
+ * Move paths into a fresh `$DSH_HOME/session-trash-<stamp>` folder.
431
+ *
432
+ * This is the fast half of a retire: a same-volume rename costs microseconds,
433
+ * while the shell's recycle operation costs ~600 ms. The caller reports the
434
+ * delete as done after this, so the wait never reaches the user.
435
+ *
436
+ * @returns `{ moved, root }` — the source paths and the staging folder, or a null
437
+ * root when the folder could not be created.
438
+ */
439
+ async function stageToTrash(targets) {
440
+ if (targets.length === 0) return { moved: [], root: null }
441
+ const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 17)
442
+ const root = path.join(dshHome(), `session-trash-${stamp}-${process.pid}-${retireCounter++}`)
443
+ try {
444
+ await fsp.mkdir(root, { recursive: true })
445
+ } catch {
446
+ return { moved: [], root: null }
447
+ }
448
+ const moved = []
449
+ for (const target of targets) {
450
+ const destination = await freeDestination(root, path.basename(target))
451
+ if (destination === undefined) continue
452
+ try {
453
+ await fsp.rename(target, destination)
454
+ moved.push(target)
455
+ continue
456
+ } catch {
457
+ // A cross-volume rename fails; copy then drop the original.
458
+ }
459
+ try {
460
+ await fsp.cp(target, destination, { recursive: true, force: false, errorOnExist: true })
461
+ await fsp.rm(target, { recursive: true, force: true })
462
+ moved.push(target)
463
+ } catch {
464
+ // Leave it: a path that cannot be retired is reported by the caller.
465
+ }
466
+ }
467
+ return { moved, root: moved.length > 0 ? root : null }
468
+ }
469
+
470
+ /** Keeps two retires in the same millisecond out of one staging folder. */
471
+ let retireCounter = 0
472
+
473
+ /** The staging move alone, for callers that just want the paths out of the way. */
474
+ async function moveToSessionTrash(targets) {
475
+ return (await stageToTrash(targets)).moved
476
+ }
477
+
478
+ /**
479
+ * Retire paths for good. The caller gets control back as soon as the paths are
480
+ * out of their original location — a same-volume rename — and the Recycle Bin
481
+ * move finishes in the background.
482
+ *
483
+ * That order is deliberate: the shell's recycle operation costs ~600 ms, which
484
+ * is exactly the wait a delete should not have. If the background call fails, the
485
+ * paths are still in `session-trash-<stamp>` and recoverable by hand; nothing is
486
+ * ever unlinked.
487
+ */
488
+ async function retirePaths(targets) {
489
+ if (targets.length === 0) return []
490
+ const staged = await stageToTrash(targets)
491
+ if (staged.root !== null) {
492
+ // Fire and forget: never awaited, never allowed to reject into the caller.
493
+ try {
494
+ sendToRecycleBin([staged.root]).catch(() => {})
495
+ } catch {
496
+ // the staged copy stays where it is
497
+ }
498
+ }
499
+ return staged.moved
500
+ }
501
+
502
+ /**
503
+ * Remove paths outright. This is the branch behind the unchecked Recycle Bin
504
+ * switch: the dialog says the delete is permanent in that state, so the files
505
+ * must not linger anywhere. Every other path through this plugin retires to the
506
+ * bin, and that difference is the whole point of the switch.
507
+ *
508
+ * @returns the paths that are gone afterwards.
509
+ */
510
+ function removeForever(targets) {
511
+ const gone = []
512
+ for (const target of targets) {
513
+ if (!fs.existsSync(target)) continue
514
+ try {
515
+ fs.rmSync(target, { recursive: true, force: true })
516
+ if (!fs.existsSync(target)) gone.push(target)
517
+ } catch {
518
+ // reported by the caller's own existence checks
519
+ }
520
+ }
521
+ return gone
522
+ }
523
+ /**
524
+ * Retire a list according to the switch: into the system trash (staged first,
525
+ * then the shell takes it) or off the disk. Kept separate from the delete so the
526
+ * choice itself can be tested without standing up a whole session.
527
+ */
528
+ async function retireTargets(targets, recycle) {
529
+ return recycle ? retirePaths(targets) : removeForever(targets)
530
+ }
531
+ async function retireSessionDirs(sessionId) {
532
+ return retirePaths(findSessionDirs(sessionId))
533
+ }
534
+
535
+ // Deleting the on-disk directory is not enough: projection caches keep a
536
+ // per-session JSON row (`$DSH_HOME/storages/<store>/sessions/<id>.json`) that
537
+ // would linger as a ghost — the sidebar list is directory-backed, so the row
538
+ // can never be shown or deleted again (issue: "can't delete anymore"). Retire
539
+ // the session's cache units together with its directories.
540
+ function findSessionCaches(sessionId) {
541
+ const storesRoot = path.join(dshHome(), 'storages')
542
+ const found = []
543
+ let stores
544
+ try {
545
+ stores = fs.readdirSync(storesRoot, { withFileTypes: true })
546
+ } catch {
547
+ return found
548
+ }
549
+ const names = idVariants(sessionId).map((variant) => `${variant}.json`)
550
+ for (const store of stores) {
551
+ if (!store.isDirectory()) continue
552
+ const dir = path.join(storesRoot, store.name, 'sessions')
553
+ let entries
554
+ try {
555
+ entries = fs.readdirSync(dir)
556
+ } catch {
557
+ continue
558
+ }
559
+ for (const entry of entries) {
560
+ if (!names.includes(entry)) continue
561
+ found.push(path.join(dir, entry))
562
+ }
563
+ }
564
+ return found
565
+ }
566
+
567
+ async function retireSessionCaches(sessionId) {
568
+ return retirePaths(findSessionCaches(sessionId))
569
+ }
570
+
571
+ // --- live state --------------------------------------------------------------
572
+
573
+ // Stop a running agent before its session disappears: cancel the active turn
574
+ // and wait, time-boxed, so a stuck driver never blocks the deletion.
575
+ async function quiesceAgent(ctx, sessionId) {
576
+ const agents = ctx.get('agents')
577
+ if (!agents || typeof agents.get !== 'function') return false
578
+ const agent = agents.get(sessionId)
579
+ if (!agent) return false
580
+ try {
581
+ if (typeof agent.cancel === 'function') agent.cancel({ kind: 'user' })
582
+ } catch {
583
+ // agent may already be settling
584
+ }
585
+ if (typeof agent.whenIdle === 'function') {
586
+ try {
587
+ await Promise.race([agent.whenIdle(), new Promise((resolve) => setTimeout(resolve, 10000))])
588
+ } catch {
589
+ // proceed with deletion anyway
590
+ }
591
+ }
592
+ return true
593
+ }
594
+
595
+ // Flush a live session, then detach its entered record so DSH emits
596
+ // host/session-removed and the client list drops the row. The persistence
597
+ // retirement started by session/disposed is awaited before the caller unlinks
598
+ // anything, because its final drain could otherwise recreate the directory.
599
+ async function flushAndDetach(ctx, sessionId) {
600
+ const sessions = ctx.get('sessions')
601
+ let flushed = false
602
+ let detached = false
603
+ if (sessions) {
604
+ for (const variant of idVariants(sessionId)) {
605
+ const live = typeof sessions.get === 'function' ? sessions.get(variant) : undefined
606
+ if (!live) continue
607
+ if (typeof sessions.flush === 'function') {
608
+ try {
609
+ await sessions.flush(live)
610
+ flushed = true
611
+ } catch {
612
+ // the log is removed anyway
613
+ }
614
+ }
615
+ try {
616
+ const entered = sessions.store && typeof sessions.store.get === 'function' ? sessions.store.get(variant) : undefined
617
+ if (entered && typeof entered.detach === 'function') {
618
+ entered.detach()
619
+ detached = true
620
+ }
621
+ } catch {
622
+ // best effort: the directory removal below is the authority
623
+ }
624
+ }
625
+ }
626
+ const sp = ctx.get('sessionPersistence')
627
+ try {
628
+ const retirement = sp && sp.retirements && typeof sp.retirements.get === 'function' ? sp.retirements.get(sessionId) : undefined
629
+ if (retirement && typeof retirement.then === 'function') await retirement
630
+ } catch {
631
+ // no retirement registry: nothing to wait for
632
+ }
633
+ return { flushed, detached }
634
+ }
635
+
636
+ // Probe the persistence write lease. Holding it proves no active writer is
637
+ // around; it is released immediately. Detaching a live session releases its
638
+ // lease asynchronously (session/disposed starts a persistence retirement), so
639
+ // the probe is retried with a short backoff before the request is refused -
640
+ // in practice the first click then succeeds without forcing anything.
641
+ // The backoff is short (200ms x 12 = ~2.2s worst case) so a batch containing
642
+ // live sessions stays responsive while the lease retirement lands.
643
+ const BUSY_RETRY_ATTEMPTS = 12
644
+ const BUSY_RETRY_DELAY_MS = 200
645
+
646
+ function sleep(ms) {
647
+ return new Promise((resolve) => setTimeout(resolve, ms))
648
+ }
649
+
650
+ async function assertNoActiveWriter(ctx, sessionId) {
651
+ const sp = ctx.get('sessionPersistence')
652
+ if (!sp || typeof sp.open !== 'function') return false
653
+ for (let attempt = 1; attempt <= BUSY_RETRY_ATTEMPTS; attempt += 1) {
654
+ let handle = null
655
+ let busy = false
656
+ try {
657
+ handle = await sp.open(sessionId, 'write')
658
+ } catch (error) {
659
+ const message = String((error && error.message) || error)
660
+ if (/own|busy|lock|hold|writer/i.test(message)) {
661
+ busy = true
662
+ } else {
663
+ return false
664
+ }
665
+ } finally {
666
+ try {
667
+ if (handle && typeof handle.close === 'function') await handle.close()
668
+ } catch {
669
+ // lease release failure is harmless: the directory is removed next
670
+ }
671
+ }
672
+ if (!busy) return true
673
+ if (attempt < BUSY_RETRY_ATTEMPTS) await sleep(BUSY_RETRY_DELAY_MS)
674
+ }
675
+ throw new HttpError(409, 'busy', 'session is currently open in DSH')
676
+ }
677
+
678
+ // Bounded concurrency for batch deletes. Different sessions are independent
679
+ // (agent quiesce, lease probe and directory sweep all key off the session id),
680
+ // so the pipeline runs in parallel through a small pool. The one shared
681
+ // mutation - workspace accounting - is serialized through withWorkspaceLock so
682
+ // two deletions can never interleave on the same store.
683
+ //
684
+ // 6 is measured, not guessed: on 64 sessions of ~2MB the wall time was
685
+ // 281ms at 4, 189ms at 6 and 142ms at 8 (the I/O parallelism saturates around
686
+ // 8), so 6 keeps a ~33% gain over 4 while staying below the saturation knee
687
+ // and limiting the number of simultaneous lease-probe loops.
688
+ const BATCH_CONCURRENCY = 6
689
+
690
+ let workspaceLock = Promise.resolve()
691
+ function withWorkspaceLock(fn) {
692
+ const run = workspaceLock.then(fn, fn)
693
+ workspaceLock = run.then(() => undefined, () => undefined)
694
+ return run
695
+ }
696
+
697
+ async function runWithConcurrency(items, limit, worker) {
698
+ const results = new Array(items.length)
699
+ let cursor = 0
700
+ const runners = []
701
+ for (let i = 0; i < Math.min(limit, items.length); i += 1) {
702
+ runners.push((async () => {
703
+ while (true) {
704
+ const index = cursor
705
+ cursor += 1
706
+ if (index >= items.length) return
707
+ results[index] = await worker(items[index], index)
708
+ }
709
+ })())
710
+ }
711
+ await Promise.all(runners)
712
+ return results
713
+ }
714
+
715
+ async function detachFromWorkspace(ctx, sessionId) {
716
+ const workspace = ctx.get('workspaceRegistry')
717
+ if (!workspace) return false
718
+ const variants = idVariants(sessionId)
719
+ let touched = false
720
+ try {
721
+ if (typeof workspace.list === 'function') {
722
+ for (const entry of workspace.list()) {
723
+ if (!entry || !Array.isArray(entry.sessionIds)) continue
724
+ if (!variants.some((variant) => entry.sessionIds.includes(variant))) continue
725
+ try {
726
+ await entry.detachSession(sessionId)
727
+ touched = true
728
+ } catch {
729
+ // keep going: the header index cleanup below still applies
730
+ }
731
+ }
732
+ }
733
+ } catch {
734
+ // registry unavailable
735
+ }
736
+ try {
737
+ if (workspace.sessionPaths && typeof workspace.sessionPaths.delete === 'function') {
738
+ for (const variant of variants) workspace.sessionPaths.delete(variant)
739
+ }
740
+ } catch {
741
+ // private map absent on this version
742
+ }
743
+ try {
744
+ if (workspace.headers && typeof workspace.headers.delete === 'function') {
745
+ for (const variant of variants) workspace.headers.delete(variant)
746
+ }
747
+ } catch {
748
+ // private map absent on this version
749
+ }
750
+ return touched
751
+ }
752
+
753
+ // --- core delete -------------------------------------------------------------
754
+
755
+ async function deleteSession(ctx, sessionId, options) {
756
+ if (!SESSION_ID_RE.test(sessionId)) {
757
+ throw new HttpError(400, 'invalid', 'invalid session id')
758
+ }
759
+ // Undoable by default: only an explicit `recycle: false` sends the files to a
760
+ // plain removal instead of the system trash.
761
+ const recycle = options === undefined || options === null || options.recycle !== false
762
+ // Subagent sessions are sessions of their own; the ones the caller ticked are
763
+ // taken with their parent. Anything that is not a well-formed id is dropped
764
+ // here, before it reaches the filesystem.
765
+ const childSessionIds = options !== undefined && options !== null && Array.isArray(options.childSessionIds)
766
+ ? options.childSessionIds
767
+ .filter((id) => typeof id === 'string' && SESSION_ID_RE.test(id))
768
+ .filter((id) => bareSessionId(id) !== bareSessionId(sessionId))
769
+ : []
770
+ const stopped = await quiesceAgent(ctx, sessionId)
771
+ const { flushed, detached } = await flushAndDetach(ctx, sessionId)
772
+ await assertNoActiveWriter(ctx, sessionId)
773
+
774
+ // Retire the on-disk directories first, then the cache rows. With the Recycle
775
+ // Bin switch on (the default) they are staged and the shell moves them to the
776
+ // bin in the background; switched off, they are removed outright — that is what
777
+ // the dialog promises in that state.
778
+ const { removed, caches } = await retireSessionFiles(sessionId, recycle)
779
+
780
+ const sp = ctx.get('sessionPersistence')
781
+ if (sp && typeof sp.stat === 'function') {
782
+ const after = await sp.stat(sessionId).catch(() => undefined)
783
+ if (after) {
784
+ throw new HttpError(500, 'verify-failed', 'session is still visible to the persistence service after deletion')
785
+ }
786
+ }
787
+ const leftover = findSessionDirs(sessionId)
788
+ if (leftover.length > 0) {
789
+ throw new HttpError(500, 'verify-failed', 'session directories could not be fully removed')
790
+ }
791
+
792
+ const workspaceDetached = await withWorkspaceLock(() => detachFromWorkspace(ctx, sessionId))
793
+ if (removed === 0 && !workspaceDetached && !flushed && !detached && caches === 0) {
794
+ throw new HttpError(404, 'not-found', 'session not found')
795
+ }
796
+
797
+ // Children last, and one failure never takes the parent result down with it:
798
+ // the parent is what the user clicked, so that click has to land.
799
+ const children = []
800
+ for (const childId of childSessionIds) {
801
+ try {
802
+ // A subagent can still be running while its parent is deleted. Removing the
803
+ // log out from under it is what made the agent's next write fail with ENOENT,
804
+ // so a child gets the same guard as the parent: stop it, flush it, and wait
805
+ // for the write lease before a single byte moves.
806
+ await quiesceAgent(ctx, childId)
807
+ await flushAndDetach(ctx, childId)
808
+ await assertNoActiveWriter(ctx, childId)
809
+ const childFiles = await retireSessionFiles(childId, recycle)
810
+ await withWorkspaceLock(() => detachFromWorkspace(ctx, childId))
811
+ children.push({ id: childId, removed: childFiles.removed, caches: childFiles.caches })
812
+ } catch (error) {
813
+ // Never delete a child that could not be quieted: something is still writing
814
+ // to it. Report it so the caller can try again once it settles.
815
+ const busy = error instanceof HttpError && error.code === 'busy'
816
+ children.push({
817
+ id: childId,
818
+ removed: 0,
819
+ caches: 0,
820
+ skipped: busy ? 'busy' : 'error',
821
+ error: String((error && error.message) || error),
822
+ })
823
+ }
824
+ }
825
+
826
+ return {
827
+ removed,
828
+ caches,
829
+ stopped,
830
+ flushed,
831
+ detached,
832
+ workspaceDetached,
833
+ children,
834
+ }
835
+ }
836
+
837
+ /**
838
+ * Take one session off the disk: its directories and its cache rows, then any
839
+ * directory the drain recreated. Shared by the parent and every child, so a
840
+ * subagent is retired exactly like the conversation the user clicked.
841
+ *
842
+ * @returns how many paths went away, and how many cache rows are now gone.
843
+ */
844
+ async function retireSessionFiles(sessionId, recycle) {
845
+ const cacheFiles = findSessionCaches(sessionId)
846
+ const targets = [...findSessionDirs(sessionId), ...cacheFiles]
847
+ let gone = await retireTargets(targets, recycle)
848
+ await new Promise((resolve) => setImmediate(resolve))
849
+ gone = gone.concat(await retireTargets(findSessionDirs(sessionId), recycle))
850
+ return { removed: gone.length, caches: cacheFiles.filter((file) => !fs.existsSync(file)).length }
851
+ }
852
+
853
+ // --- artifacts: what a session touched, and quarantining it -----------------
854
+ //
855
+ // "Produced files" is derived from the durable session log alone: the log is the
856
+ // only record that outlives a closed Session (the host's own observation state
857
+ // lives in a plugin-local WeakMap and dies with the process, and the
858
+ // `workspace/changes` summaries live in a temporary directory that disposal
859
+ // removes). Classification rests on one invariant of the default
860
+ // fs-observation-policy: `write` may not overwrite a file that was not read
861
+ // first, and `edit` requires a prior read. So a write whose path has no earlier
862
+ // successful read CREATED the file; anything else already existed.
863
+ //
864
+ // Nothing here deletes. Files are moved into a timestamped quarantine directory
865
+ // under $DSH_HOME, keeping their path relative to the session's working
866
+ // directory, so a wrong call is recoverable.
867
+
868
+ const QUARANTINE_PREFIX = 'purge-quarantine'
869
+ const MAX_LISTED = 500
870
+ /**
871
+ * How many distinct paths one scan will resolve. Every path costs a realpath,
872
+ * and a session that walked a large tree can name tens of thousands of them;
873
+ * the dialog would sit on "scanning" for as long as they take. Past this the
874
+ * plan reports `truncated`, which the dialog already surfaces.
875
+ */
876
+ const MAX_SCANNED = 2000
877
+ /** How many path resolutions run at once: enough to hide the threadpool round trip, few enough to stay polite. */
878
+ const RESOLVE_CONCURRENCY = 16
879
+ /** How many directories the folder picker lists before saying there are more. */
880
+ const MAX_BROWSE_ENTRIES = 500
881
+ /** How long the OS chooser may stay open before the request gives up on it. */
882
+ const PICK_TIMEOUT_MS = 5 * 60 * 1000
883
+ /** How long a shell helper (the recycle-bin script) may run before giving up. */
884
+ const SHELL_TIMEOUT_MS = 5 * 60 * 1000
885
+
886
+ /** Run a program and collect its output, leaving the meaning of the exit to the caller. */
887
+ function runExecutable(program, args, timeoutMs) {
888
+ return new Promise((resolve, reject) => {
889
+ const child = spawn(program, args, { windowsHide: true })
890
+ let out = ''
891
+ let err = ''
892
+ let settled = false
893
+ const finish = (fn, value) => {
894
+ if (settled) return
895
+ settled = true
896
+ clearTimeout(timer)
897
+ fn(value)
898
+ }
899
+ const timer = setTimeout(() => {
900
+ try { child.kill() } catch { /* already gone */ }
901
+ finish(reject, new HttpError(504, 'timeout', '等待系统对话框超时'))
902
+ }, timeoutMs)
903
+
904
+ child.stdout.on('data', (chunk) => { out += chunk.toString('utf8') })
905
+ child.stderr.on('data', (chunk) => { err += chunk.toString('utf8') })
906
+ child.on('error', (error) => {
907
+ finish(reject, new HttpError(500, 'spawn', `无法启动 ${path.basename(program)}:${String((error && error.message) || error)}`))
908
+ })
909
+ child.on('close', (code) => finish(resolve, { code, stdout: out, stderr: err }))
910
+ })
911
+ }
912
+
913
+ /** Argument keys carrying the target path, per writing tool. */
914
+ const WRITE_TOOL_PATHS = {
915
+ write: ['file_path', 'path'],
916
+ edit: ['file_path', 'path'],
917
+ str_replace_editor: ['path', 'file_path'],
918
+ create_file: ['file_path', 'path'],
919
+ }
920
+
921
+ /** Argument keys carrying the target path, per reading tool. */
922
+ const READ_TOOL_PATHS = {
923
+ read: ['file_path', 'path'],
924
+ read_file: ['file_path', 'path'],
925
+ }
926
+
927
+ /**
928
+ * Resolve the target path one tool call names.
929
+ * @param name - tool name.
930
+ * @param argumentsJson - the model's raw argument JSON.
931
+ * @param cwd - the session's recorded working directory, for relative paths.
932
+ * @returns the absolute path and whether the tool writes, or undefined.
933
+ */
934
+ function toolTarget(name, argumentsJson, cwd) {
935
+ const writes = Object.prototype.hasOwnProperty.call(WRITE_TOOL_PATHS, name)
936
+ const keys = writes ? WRITE_TOOL_PATHS[name] : READ_TOOL_PATHS[name]
937
+ if (keys === undefined) return undefined
938
+ let args
939
+ try {
940
+ args = JSON.parse(typeof argumentsJson === 'string' ? argumentsJson : '')
941
+ } catch {
942
+ return undefined
943
+ }
944
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) return undefined
945
+ const raw = keys.map((key) => args[key]).find((value) => typeof value === 'string' && value.trim() !== '')
946
+ if (raw === undefined) return undefined
947
+ let absolute
948
+ if (path.isAbsolute(raw)) absolute = raw
949
+ else if (cwd === undefined) return undefined
950
+ else absolute = path.resolve(cwd, raw)
951
+ return { path: absolute, writes }
952
+ }
953
+
954
+ /** Read a stored session's events through the persistence seam. */
955
+ async function readSessionEvents(ctx, sessionId) {
956
+ const sp = ctx.get('sessionPersistence')
957
+ if (!sp || typeof sp.open !== 'function') {
958
+ return { events: [], warning: '持久化服务不可用,无法读取会话日志' }
959
+ }
960
+ let handle = null
961
+ try {
962
+ handle = await sp.open(sessionId, 'read')
963
+ const result = await handle.read()
964
+ const events = Array.isArray(result && result.events) ? result.events : []
965
+ return { events, warning: undefined }
966
+ } catch (error) {
967
+ return { events: [], warning: `读取会话日志失败:${String((error && error.message) || error)}` }
968
+ } finally {
969
+ try {
970
+ if (handle && typeof handle.close === 'function') await handle.close()
971
+ } catch {
972
+ // a close failure must not change the plan
973
+ }
974
+ }
975
+ }
976
+
977
+ /**
978
+ * Identity of one path for "have we seen this file before?" purposes. The real
979
+ * path when it resolves, so a symlink alias and its target count as the same
980
+ * file; otherwise a case-folded resolved path on Windows, whose filesystem does
981
+ * not distinguish `Foo.md` from `foo.md`. Comparing spellings instead would let
982
+ * a write through an alias look like a creation.
983
+ * @param absolute - the path a tool call named.
984
+ * @param cache - optional per-scan memo; without it the resolution cost scales
985
+ * with log length rather than with the number of distinct files.
986
+ * @returns a stable key for the file, not for the spelling.
987
+ */
988
+ async function identityKey(absolute, cache) {
989
+ if (cache !== undefined) {
990
+ const hit = cache.get(absolute)
991
+ if (hit !== undefined) return hit
992
+ }
993
+ let key
994
+ try {
995
+ key = await realpathNative(absolute)
996
+ } catch {
997
+ const resolved = path.resolve(absolute)
998
+ key = process.platform === 'win32' ? resolved.toLowerCase() : resolved
999
+ }
1000
+ if (cache !== undefined) cache.set(absolute, key)
1001
+ return key
1002
+ }
1003
+
1004
+ /**
1005
+ * Every path this session's writing tools touched, split by whether the session
1006
+ * created it or found it already there.
1007
+ * @param events - stored session events, in order.
1008
+ * @param cwd - the session's recorded working directory.
1009
+ * @param cache - optional per-scan memo for path resolution, shared across calls.
1010
+ * @returns `{ created, modified }`, keyed by file identity, each row `{ path, identity, ops }`.
1011
+ */
1012
+ async function collectSessionPaths(events, cwd, cache) {
1013
+ const pending = new Map()
1014
+ const read = new Set()
1015
+ const created = new Map()
1016
+ const modified = new Map()
1017
+ const memo = cache !== undefined ? cache : new Map()
1018
+
1019
+ // Resolve every distinct path the log names first, together. A long session
1020
+ // names the same handful of files thousands of times, so awaiting per call
1021
+ // would buy one threadpool round trip per mention; this buys one per file.
1022
+ const named = new Set()
1023
+ let overflow = false
1024
+ for (const event of events) {
1025
+ const data = event && event.data
1026
+ if (!data || typeof data !== 'object' || event.type !== 'tool/call') continue
1027
+ const target = toolTarget(typeof data.name === 'string' ? data.name : '', data.arguments, cwd)
1028
+ if (target === undefined) continue
1029
+ if (named.size >= MAX_SCANNED && !named.has(target.path)) {
1030
+ overflow = true
1031
+ break
1032
+ }
1033
+ named.add(target.path)
1034
+ }
1035
+ await runWithConcurrency([...named], RESOLVE_CONCURRENCY, async (absolute) => {
1036
+ await identityKey(absolute, memo)
1037
+ })
1038
+
1039
+ const commit = (call) => {
1040
+ // A file the session created and later edited stays "created": one identity
1041
+ // must never sit in both buckets, or a scope=all run would target it twice
1042
+ // and report a spurious failure for the second attempt.
1043
+ const alreadyCreated = created.get(call.identity)
1044
+ if (alreadyCreated !== undefined) {
1045
+ alreadyCreated.ops += 1
1046
+ return
1047
+ }
1048
+ const bucket = call.existedBefore ? modified : created
1049
+ const prior = bucket.get(call.identity)
1050
+ if (prior !== undefined) prior.ops += 1
1051
+ else bucket.set(call.identity, { path: call.path, identity: call.identity, ops: 1 })
1052
+ }
1053
+
1054
+ for (const event of events) {
1055
+ const data = event && event.data
1056
+ if (!data || typeof data !== 'object') continue
1057
+
1058
+ if (event.type === 'tool/call') {
1059
+ const name = typeof data.name === 'string' ? data.name : ''
1060
+ const target = toolTarget(name, data.arguments, cwd)
1061
+ // Existence is decided at call time, against the reads that already
1062
+ // succeeded - the policy's own ordering - and on identity, so an alias of
1063
+ // a file the session read is still an edit.
1064
+ if (target !== undefined) {
1065
+ const identity = await identityKey(target.path, memo)
1066
+ pending.set(data.callId, {
1067
+ path: target.path,
1068
+ identity,
1069
+ writes: target.writes,
1070
+ existedBefore: read.has(identity),
1071
+ })
1072
+ }
1073
+ continue
1074
+ }
1075
+
1076
+ if (event.type !== 'tool/result') continue
1077
+ const message = data.message
1078
+ const callId = message && typeof message.toolCallId === 'string' ? message.toolCallId : undefined
1079
+ if (callId === undefined) continue
1080
+ const call = pending.get(callId)
1081
+ if (call === undefined) continue
1082
+ pending.delete(callId)
1083
+ if (data.error !== undefined || (message && message.isError === true)) continue
1084
+ if (call.writes) commit(call)
1085
+ else read.add(call.identity)
1086
+ }
1087
+
1088
+ return { named: named.size, overflow, created, modified }
1089
+ }
1090
+
1091
+ /**
1092
+ * Whether `child` is strictly inside `parent`, comparing real paths. Folded on
1093
+ * Windows, where the filesystem ignores case: a realpath does not normalise the
1094
+ * case of a prefix that still matches a differently-spelled spelling.
1095
+ */
1096
+ function insidePath(parent, child) {
1097
+ if (parent === child) return false
1098
+ const fold = (value) => (process.platform === 'win32' ? value.toLowerCase() : value)
1099
+ const base = fold(parent)
1100
+ const prefix = base.endsWith(path.sep) ? base : base + path.sep
1101
+ return fold(child).startsWith(prefix)
1102
+ }
1103
+
1104
+ /**
1105
+ * Is this directory inside a git working tree? A `.git` entry marks the root —
1106
+ * a directory in a normal clone, a file in a worktree or a submodule.
1107
+ *
1108
+ * The walk memoises per directory: one plan can span hundreds of files that share
1109
+ * a handful of folders, and each miss would otherwise stat every level again.
1110
+ */
1111
+ async function isInsideGitRepo(directory, cache) {
1112
+ let current = path.resolve(directory)
1113
+ const walked = []
1114
+ for (;;) {
1115
+ if (cache.has(current)) {
1116
+ const verdict = cache.get(current)
1117
+ for (const dir of walked) cache.set(dir, verdict)
1118
+ return verdict
1119
+ }
1120
+ walked.push(current)
1121
+ try {
1122
+ const marker = await fsp.stat(path.join(current, '.git'))
1123
+ if (marker.isDirectory() || marker.isFile()) {
1124
+ for (const dir of walked) cache.set(dir, true)
1125
+ return true
1126
+ }
1127
+ } catch {
1128
+ // no .git here; keep walking up
1129
+ }
1130
+ const parent = path.dirname(current)
1131
+ if (parent === current) {
1132
+ for (const dir of walked) cache.set(dir, false)
1133
+ return false
1134
+ }
1135
+ current = parent
1136
+ }
1137
+ }
1138
+
1139
+ /**
1140
+ * Keep only the paths that may actually be moved: an existing regular file whose
1141
+ * real path is strictly inside the session's working directory and outside the
1142
+ * DSH home. Every rejection carries its reason.
1143
+ * @param rows - candidate rows `{ path, ops }`.
1144
+ * @param cwd - the session's recorded working directory.
1145
+ * @param home - resolved DSH home.
1146
+ * @param options - `{ skipGit }`: also refuse files inside a git working tree.
1147
+ * @returns `{ allowed, refused }`.
1148
+ */
1149
+ async function classifyPaths(rows, cwd, home, options) {
1150
+ const allowed = []
1151
+ const refused = []
1152
+ const skipGit = options !== undefined && options !== null && options.skipGit === true
1153
+ const gitCache = new Map()
1154
+ const list = [...rows.values()]
1155
+ if (cwd === undefined) {
1156
+ for (const row of list) refused.push({ path: row.path, reason: '会话未记录工作目录,无法安全定位' })
1157
+ return { allowed, refused }
1158
+ }
1159
+ let realCwd
1160
+ try {
1161
+ realCwd = await fsp.realpath(cwd)
1162
+ } catch {
1163
+ for (const row of list) refused.push({ path: row.path, reason: '会话工作目录已不存在,无法校验归属' })
1164
+ return { allowed, refused }
1165
+ }
1166
+ let realHome = home
1167
+ try {
1168
+ realHome = await fsp.realpath(home)
1169
+ } catch {
1170
+ // an absent home cannot contain anything that exists
1171
+ }
1172
+ // Resolve each row's stat and real path together rather than one after another:
1173
+ // a long session can list hundreds of files, and awaiting them serially turns
1174
+ // one threadpool round trip into hundreds. `runWithConcurrency` keeps the order.
1175
+ const verdicts = await runWithConcurrency(list, RESOLVE_CONCURRENCY, async (row) => {
1176
+ let info
1177
+ try {
1178
+ info = await fsp.stat(row.path)
1179
+ } catch {
1180
+ return { refuse: { path: row.path, reason: '文件已不存在' } }
1181
+ }
1182
+ if (!info.isFile()) return { refuse: { path: row.path, reason: '不是普通文件,已跳过' } }
1183
+ let real
1184
+ try {
1185
+ real = await fsp.realpath(row.path)
1186
+ } catch {
1187
+ return { refuse: { path: row.path, reason: '无法解析真实路径,已跳过' } }
1188
+ }
1189
+ if (!insidePath(realCwd, real)) {
1190
+ return { refuse: { path: row.path, reason: '不在该对话的工作目录内,已跳过' } }
1191
+ }
1192
+ if (insidePath(realHome, real)) {
1193
+ return { refuse: { path: row.path, reason: '位于 DSH 数据目录内,已跳过' } }
1194
+ }
1195
+ if (skipGit && await isInsideGitRepo(path.dirname(real), gitCache)) {
1196
+ return { refuse: { path: row.path, reason: '位于 git 仓库内,已跳过' } }
1197
+ }
1198
+ return { allow: { path: real, displayPath: row.path, ops: row.ops, bytes: info.size, mtime: info.mtimeMs } }
1199
+ })
1200
+ for (const verdict of verdicts) {
1201
+ if (verdict.allow !== undefined) allowed.push(verdict.allow)
1202
+ else refused.push(verdict.refuse)
1203
+ }
1204
+ return { allowed, refused }
1205
+ }
1206
+
1207
+ /**
1208
+ * Build the artifact plan for one session.
1209
+ * @param ctx - host plugin context.
1210
+ * @param sessionId - validated session id.
1211
+ * @returns `{ cwd, created, modified, refused, truncated, warnings }`.
1212
+ */
1213
+ async function planArtifacts(ctx, sessionId, cache, options) {
1214
+ const home = dshHome()
1215
+ const warnings = []
1216
+ const sp = ctx.get('sessionPersistence')
1217
+ let cwd
1218
+ if (sp && typeof sp.stat === 'function') {
1219
+ try {
1220
+ const snapshot = await sp.stat(sessionId)
1221
+ let header = null
1222
+ if (snapshot !== null && typeof snapshot === 'object') {
1223
+ header = snapshot.header !== null && typeof snapshot.header === 'object' ? snapshot.header : snapshot
1224
+ }
1225
+ if (header && typeof header.cwd === 'string' && header.cwd !== '') cwd = header.cwd
1226
+ } catch (error) {
1227
+ warnings.push(`未找到该会话的存储记录:${String((error && error.message) || error)}`)
1228
+ }
1229
+ }
1230
+ const { events, warning } = await readSessionEvents(ctx, sessionId)
1231
+ if (warning !== undefined) warnings.push(warning)
1223
1232
  const scan = await collectSessionPaths(events, cwd, cache)
1224
- const { created, modified } = scan
1225
- const createdPlan = await classifyPaths(created, cwd, home, options)
1226
- const modifiedPlan = await classifyPaths(modified, cwd, home, options)
1227
- const refused = [...createdPlan.refused, ...modifiedPlan.refused]
1228
- return {
1229
- // Stamped so a caller handing this plan back cannot smuggle in another
1230
- // session's list: runQuarantine refuses a plan that does not belong here.
1231
- sessionId,
1232
- cwd,
1233
- created: createdPlan.allowed.slice(0, MAX_LISTED),
1234
- modified: modifiedPlan.allowed.slice(0, MAX_LISTED),
1235
- refused: refused.slice(0, MAX_LISTED),
1233
+ const { created, modified } = scan
1234
+ const createdPlan = await classifyPaths(created, cwd, home, options)
1235
+ const modifiedPlan = await classifyPaths(modified, cwd, home, options)
1236
+ const refused = [...createdPlan.refused, ...modifiedPlan.refused]
1237
+ return {
1238
+ // Stamped so a caller handing this plan back cannot smuggle in another
1239
+ // session's list: runQuarantine refuses a plan that does not belong here.
1240
+ sessionId,
1241
+ cwd,
1242
+ created: createdPlan.allowed.slice(0, MAX_LISTED),
1243
+ modified: modifiedPlan.allowed.slice(0, MAX_LISTED),
1244
+ refused: refused.slice(0, MAX_LISTED),
1236
1245
  truncated: scan.overflow
1237
- || createdPlan.allowed.length > MAX_LISTED
1238
- || modifiedPlan.allowed.length > MAX_LISTED
1239
- || refused.length > MAX_LISTED,
1240
- warnings,
1241
- }
1242
- }
1243
-
1244
- /**
1245
- * Claim a quarantine directory under the DSH home. The name carries second
1246
- * resolution only, so two deletes can land on the same name; an exclusive mkdir
1247
- * (never `recursive: true`, which would happily reuse an existing tree) decides
1248
- * the winner and the loser retries with a suffix. Two runs therefore can never
1249
- * share a tree, which is what stops one run's file from overwriting another's.
1250
- * @param home - resolved DSH home.
1251
- * @returns the claimed directory, or undefined when none could be claimed.
1252
- */
1253
- async function claimQuarantineDirectory(home) {
1254
- // A fresh home has no quarantine root yet; creating it is the only write this
1255
- // side does outside the quarantine tree, and it keeps a missing home from
1256
- // turning into a silent "cannot claim" on the very first delete.
1257
- try {
1258
- await fsp.mkdir(home, { recursive: true })
1259
- } catch {
1260
- return undefined
1261
- }
1262
- const base = `${QUARANTINE_PREFIX}-${new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)}`
1263
- for (let attempt = 0; attempt < 1000; attempt += 1) {
1264
- const candidate = path.join(home, attempt === 0 ? base : `${base}-${attempt}`)
1265
- try {
1266
- await fsp.mkdir(candidate, { recursive: false })
1267
- return candidate
1268
- } catch (error) {
1269
- if (error && error.code === 'EEXIST') continue
1270
- return undefined
1271
- }
1272
- }
1273
- return undefined
1274
- }
1275
-
1276
- /** Whether a path exists, without throwing. */
1277
- async function pathExists(target) {
1278
- try {
1279
- await fsp.access(target)
1280
- return true
1281
- } catch {
1282
- return false
1283
- }
1284
- }
1285
-
1286
- /**
1287
- * A destination inside the quarantine tree that does not already exist. The
1288
- * move itself must never overwrite: a quarantine that silently replaced an
1289
- * earlier copy would destroy the only surviving copy of the file it replaced.
1290
- * @param directory - claimed quarantine directory.
1291
- * @param relative - path relative to the session's working directory.
1292
- * @returns a free absolute path, or undefined when every name was taken.
1293
- */
1294
- async function freeDestination(directory, relative) {
1295
- const first = path.join(directory, relative)
1296
- if (!(await pathExists(first))) return first
1297
- const dir = path.dirname(first)
1298
- const ext = path.extname(first)
1299
- const stem = path.basename(first, ext)
1300
- for (let n = 1; n < 10000; n += 1) {
1301
- const candidate = path.join(dir, `${stem}-${n}${ext}`)
1302
- if (!(await pathExists(candidate))) return candidate
1303
- }
1304
- return undefined
1305
- }
1306
-
1307
- /**
1308
- * Move the chosen files into a timestamped quarantine directory under the DSH
1309
- * home, preserving each path relative to the session's working directory. Files
1310
- * are moved, never removed, and an existing quarantine entry is never replaced,
1311
- * so a wrong call is always recoverable by hand.
1312
- *
1313
- * Every step is asynchronous on purpose: a cross-device move copies, and a
1314
- * synchronous copy inside the request handler would freeze the event loop, which
1315
- * means every other session's traffic stalls behind one large quarantine.
1316
- *
1317
- * @param targets - absolute file paths to move.
1318
- * @param cwd - the session's recorded working directory.
1319
- * @param home - resolved DSH home.
1320
- * @returns `{ directory, moved, failed }`.
1321
- */
1322
- async function quarantineFiles(targets, cwd, home) {
1323
- const moved = []
1324
- const failed = []
1325
- if (targets.length === 0) return { directory: null, moved, failed }
1326
-
1327
- const directory = await claimQuarantineDirectory(home)
1328
- if (directory === undefined) {
1329
- for (const target of targets) failed.push({ path: target, error: '无法创建隔离目录' })
1330
- return { directory: null, moved, failed }
1331
- }
1332
-
1333
- let realCwd = cwd
1334
- if (typeof cwd === 'string') {
1335
- try {
1336
- realCwd = await fsp.realpath(cwd)
1337
- } catch {
1338
- // keep the recorded spelling; classifyPaths already proved containment
1339
- }
1340
- }
1341
- for (const target of targets) {
1342
- let relative = path.basename(target)
1343
- if (typeof realCwd === 'string') {
1344
- const candidate = path.relative(realCwd, target)
1345
- if (candidate !== '' && !candidate.startsWith('..') && !path.isAbsolute(candidate)) relative = candidate
1346
- }
1347
- try {
1348
- await fsp.mkdir(path.dirname(path.join(directory, relative)), { recursive: true })
1349
- const destination = await freeDestination(directory, relative)
1350
- if (destination === undefined) {
1351
- failed.push({ path: target, error: '隔离目录内没有可用的目标文件名' })
1352
- continue
1353
- }
1354
- try {
1355
- await fsp.rename(target, destination)
1356
- } catch {
1357
- // A cross-device rename fails; fall back to copy-then-remove. `COPYFILE_EXCL`
1358
- // keeps the copy from replacing anything that appeared in between.
1359
- await fsp.copyFile(target, destination, fs.constants.COPYFILE_EXCL)
1360
- await fsp.rm(target, { force: true })
1361
- }
1362
- moved.push({ from: target, to: destination })
1363
- } catch (error) {
1364
- failed.push({ path: target, error: String((error && error.message) || error) })
1365
- }
1366
- }
1367
- return { directory, moved, failed }
1368
- }
1369
-
1370
- /**
1371
- * The files one plan actually offered. The per-file delete button sends back a
1372
- * path from this list, and the route refuses anything else: a request cannot
1373
- * name a file the user was never shown.
1374
- *
1375
- * @param plan - the artifact plan this plugin produced for a session.
1376
- * @returns every listed path, created and modified alike.
1377
- */
1378
- function artifactCandidates(plan) {
1379
- const out = []
1380
- for (const group of [plan.created, plan.modified]) {
1381
- if (!Array.isArray(group)) continue
1382
- for (const row of group) {
1383
- if (row !== null && row !== undefined && typeof row.path === 'string') out.push(row.path)
1384
- }
1385
- }
1386
- return out
1387
- }
1388
-
1389
- /**
1390
- * The path a per-file delete may touch: one the plan listed, nothing else.
1391
- * Without this the button would be a general-purpose delete primitive reachable
1392
- * from the page.
1393
- *
1394
- * @param plan - the artifact plan for the session.
1395
- * @param target - the path the page asked for.
1396
- * @returns the resolved path, ready to unlink.
1397
- */
1398
- function assertListedPath(plan, target) {
1399
- const resolved = path.resolve(target)
1400
- const listed = artifactCandidates(plan).some((candidate) => path.resolve(candidate) === resolved)
1401
- if (!listed) throw new HttpError(403, 'not-listed', '该文件不在本对话的产出清单里')
1402
- return resolved
1403
- }
1404
-
1405
- /**
1406
- * Delete one produced file. The destination is the user's call, and the dialog
1407
- * passes the same preference that governs a conversation delete: to the system
1408
- * trash, or outright.
1409
- *
1410
- * @param target - absolute path of the file.
1411
- * @param recycle - true to send it to the system recycle bin.
1412
- * @returns `{ recycled }` describing where it went.
1413
- */
1414
- async function removeOneFile(target, recycle) {
1415
- const resolved = path.resolve(target)
1416
- let info
1417
- try {
1418
- info = await fsp.lstat(resolved)
1419
- } catch (error) {
1420
- throw new HttpError(404, 'missing', `文件已不存在:${String((error && error.message) || error)}`)
1421
- }
1422
- if (!info.isFile()) throw new HttpError(400, 'not-a-file', '只能删除普通文件')
1423
- if (recycle === true) {
1424
- const ok = await sendToRecycleBin([resolved])
1425
- if (!ok) throw new HttpError(500, 'recycle', '移入回收站失败')
1426
- return { recycled: true }
1427
- }
1428
- try {
1429
- await fsp.unlink(resolved)
1430
- } catch (error) {
1431
- throw new HttpError(500, 'unlink', `删除失败:${String((error && error.message) || error)}`)
1432
- }
1433
- return { recycled: false }
1434
- }
1435
-
1436
- /**
1437
- * Quarantine the files one request selected. The candidate set is recomputed
1438
- * here from the session log and the request's paths are intersected with it, so
1439
- * a tampered request cannot move anything the user was not shown.
1440
- * @param ctx - host plugin context.
1441
- * @param sessionId - validated session id.
1442
- * @param request - `{ scope, paths }` from the client; undefined asks for none.
1443
- * @returns the outcome, or null when the request asked for no quarantine.
1444
- */
1445
- async function runQuarantine(ctx, sessionId, request, knownPlan) {
1446
- if (request === undefined || request === null || typeof request !== 'object') return null
1447
- // Validated here as well as at the route, because `internals` exposes this
1448
- // function and a direct caller must not be able to skip the check.
1449
- if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
1450
- const scope = request.scope === 'all' ? 'all' : 'created'
1451
- // The same flag the dialog was built with, so a derived set cannot contain a
1452
- // file the listing refused to show.
1453
- const skipGit = request.skipGit === true
1454
- // Re-deriving the plan is the expensive half of a delete; a caller that already
1455
- // holds it for this session hands it over instead of paying for it twice.
1456
- const plan = knownPlan === undefined || knownPlan === null
1457
- ? await planArtifacts(ctx, sessionId, undefined, { skipGit })
1458
- : knownPlan
1459
- // A handed-in plan must be this session's plan. The route always derives it
1460
- // from the same id, but `internals` exposes this function, and a future caller
1461
- // passing its neighbour's plan would move files the user never saw.
1462
- if (plan.sessionId !== sessionId) throw new HttpError(400, 'invalid', 'plan does not belong to this session')
1463
- const candidates = scope === 'all' ? [...plan.created, ...plan.modified] : [...plan.created]
1464
- const allowed = new Set(candidates.map((row) => row.path))
1465
- const requested = Array.isArray(request.paths) ? request.paths : null
1466
- const requestedStrings = requested === null ? null : new Set(requested.filter((value) => typeof value === 'string'))
1467
- const targets = requested === null
1468
- ? [...allowed]
1469
- : [...requestedStrings].filter((value) => allowed.has(value))
1470
- // Resolve the configured save path before moving a single file: a bad path must
1471
- // stop the request, not send the files somewhere unintended.
1472
- const rootInfo = await resolveQuarantineRoot(request.root, plan.cwd)
1473
- if (rootInfo.error !== undefined) throw new HttpError(400, 'invalid', rootInfo.error)
1474
- const root = rootInfo.root
1475
- const outcome = await quarantineFiles(targets, plan.cwd, root)
1476
- return {
1477
- scope,
1478
- directory: outcome.moved.length > 0 ? outcome.directory : null,
1479
- root,
1480
- moved: outcome.moved,
1481
- failed: outcome.failed,
1482
- candidates: allowed.size,
1483
- selected: targets.length,
1484
- dropped: requestedStrings === null ? 0 : requestedStrings.size - targets.length,
1485
- }
1486
- }
1487
-
1488
- /**
1489
- * Decide which directory the timestamped quarantine folder is created under. An
1490
- * empty request means the DSH home, which is what every earlier version did.
1491
- * @param requested - the directory the client asked for, if any.
1492
- * @param cwd - the session's working directory, used to refuse a "quarantine"
1493
- * that would only shuffle the files around inside the tree they came from.
1494
- * @returns `{ root }` or `{ error }`.
1495
- */
1496
- async function resolveQuarantineRoot(requested, cwd) {
1497
- const home = dshHome()
1498
- if (requested === undefined || requested === null || requested === '') return { root: home }
1499
- if (typeof requested !== 'string') return { error: '保存路径必须是字符串' }
1500
- if (requested.length > 4096) return { error: '保存路径过长' }
1501
- if (!path.isAbsolute(requested)) return { error: '保存路径必须是绝对路径' }
1502
-
1503
- let real
1504
- try {
1505
- real = await fsp.realpath(requested)
1506
- } catch {
1507
- return { error: `保存路径不存在:${requested}` }
1508
- }
1509
- let info
1510
- try {
1511
- info = await fsp.stat(real)
1512
- } catch {
1513
- return { error: `无法读取保存路径:${requested}` }
1514
- }
1515
- if (!info.isDirectory()) return { error: '保存路径不是目录' }
1516
-
1517
- // The sessions store belongs to DSH; filling it with quarantined files would
1518
- // drop them back into the one tree the delete pipeline sweeps.
1519
- const sessionsRoot = path.join(home, 'sessions')
1520
- if (real === sessionsRoot || insidePath(sessionsRoot, real)) {
1521
- return { error: '不能把隔离夹设在会话存储目录内' }
1522
- }
1523
- if (typeof cwd === 'string') {
1524
- let realCwd
1525
- try {
1526
- realCwd = await fsp.realpath(cwd)
1527
- } catch {
1528
- realCwd = undefined
1529
- }
1530
- if (realCwd !== undefined && (real === realCwd || insidePath(realCwd, real))) {
1531
- return { error: '不能把隔离夹设在会话工作目录内' }
1532
- }
1533
- }
1534
- return { root: real }
1535
- }
1536
-
1537
- /** The drive letters Windows exposes, skipping the ones that cannot be read. */
1538
- async function listDriveRoots() {
1539
- if (process.platform !== 'win32') return []
1540
- const roots = []
1541
- for (let code = 65; code <= 90; code += 1) {
1542
- const drive = `${String.fromCharCode(code)}:\\`
1543
- try {
1544
- await fsp.access(drive)
1545
- roots.push({ name: drive, path: drive })
1546
- } catch {
1547
- // absent or unreadable: not offered
1548
- }
1549
- }
1550
- return roots
1551
- }
1552
-
1553
- /**
1554
- * One directory listing for the folder picker. Directories only: the picker
1555
- * chooses where a folder is created, so files would be noise.
1556
- * @param target - absolute directory to list; the DSH home when omitted.
1557
- */
1558
- async function listDirectories(target) {
1559
- const home = dshHome()
1560
- const start = target === undefined || target === null || target === '' ? home : target
1561
- if (typeof start !== 'string') throw new HttpError(400, 'invalid', 'path must be a string')
1562
- if (!path.isAbsolute(start)) throw new HttpError(400, 'invalid', 'path must be absolute')
1563
-
1564
- let real
1565
- try {
1566
- real = await fsp.realpath(start)
1567
- } catch {
1568
- throw new HttpError(400, 'invalid', `目录不存在:${start}`)
1569
- }
1570
- let entries
1571
- try {
1572
- entries = await fsp.readdir(real, { withFileTypes: true })
1573
- } catch (error) {
1574
- throw new HttpError(400, 'invalid', `无法读取目录:${String((error && error.message) || error)}`)
1575
- }
1576
-
1577
- const directories = []
1578
- for (const entry of entries) {
1579
- if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
1580
- const full = path.join(real, entry.name)
1581
- try {
1582
- // `stat` follows a link, so a shortcut to a folder is still offered.
1583
- const info = await fsp.stat(full)
1584
- if (!info.isDirectory()) continue
1585
- } catch {
1586
- continue
1587
- }
1588
- directories.push({ name: entry.name, path: full })
1589
- }
1590
- directories.sort((a, b) => a.name.localeCompare(b.name))
1591
-
1592
- const parent = real === path.parse(real).root ? null : path.dirname(real)
1593
- return {
1594
- path: real,
1595
- parent,
1596
- entries: directories.slice(0, MAX_BROWSE_ENTRIES),
1597
- truncated: directories.length > MAX_BROWSE_ENTRIES,
1598
- // At a drive root, offer the other drives so Windows users are not stranded.
1599
- roots: parent === null ? await listDriveRoots() : [],
1600
- defaultRoot: home,
1601
- }
1602
- }
1603
-
1604
- /**
1605
- * Run one PowerShell invocation and resolve its trimmed stdout.
1606
- *
1607
- * The script is passed as a file, never on stdin: `-Command -` reads stdin with
1608
- * the console code page, and a non-ASCII byte in the script (the Chinese dialog
1609
- * description, for one) silently killed the whole run instead of erroring.
1610
- */
1611
- function runPowershell(args, timeoutMs) {
1612
- return new Promise((resolve, reject) => {
1613
- const child = spawn('powershell.exe', args, {
1614
- windowsHide: true,
1615
- })
1616
- let out = ''
1617
- let err = ''
1618
- let settled = false
1619
- const finish = (fn, value) => {
1620
- if (settled) return
1621
- settled = true
1622
- clearTimeout(timer)
1623
- fn(value)
1624
- }
1625
- const timer = setTimeout(() => {
1626
- try { child.kill() } catch { /* already gone */ }
1627
- finish(reject, new HttpError(504, 'timeout', '等待系统对话框超时'))
1628
- }, timeoutMs)
1629
-
1630
- child.stdout.on('data', (chunk) => { out += chunk.toString('utf8') })
1631
- child.stderr.on('data', (chunk) => { err += chunk.toString('utf8') })
1632
- child.on('error', (error) => {
1633
- finish(reject, new HttpError(500, 'spawn', `无法启动系统对话框:${String((error && error.message) || error)}`))
1634
- })
1635
- child.on('close', (code) => {
1636
- if (code !== 0) {
1637
- finish(reject, new HttpError(500, 'shell', `系统对话框异常退出(${code}):${err.trim().slice(0, 300)}`))
1638
- return
1639
- }
1640
- finish(resolve, out.trim())
1641
- })
1642
- })
1643
- }
1644
-
1645
- /**
1646
- * Open a directory in the operating system's file manager. The child is detached
1647
- * and unreferenced so the HTTP response returns at once and the window lives on
1648
- * its own; `explorer.exe` reports a non-zero exit even when it succeeds, so its
1649
- * status is deliberately ignored.
1650
- */
1651
- function revealDirectory(directory) {
1652
- const opener = process.platform === 'win32'
1653
- ? { program: 'explorer.exe', args: [directory] }
1654
- : process.platform === 'darwin'
1655
- ? { program: 'open', args: [directory] }
1656
- : { program: 'xdg-open', args: [directory] }
1657
- const child = spawn(opener.program, opener.args, { detached: true, stdio: 'ignore', windowsHide: false })
1658
- // Without this listener a failed spawn (explorer missing, blocked by security
1659
- // software) surfaces as an unhandled `error` event and takes the host down.
1660
- child.on('error', () => {})
1661
- child.unref()
1662
- }
1663
-
1664
- /**
1665
- * Ask the host for a directory.
1666
- *
1667
- * DSH mounts `ctx.directoryPicker` (`@deepseek-ai/dsh-host-directory-picker-auto`),
1668
- * whose capability names the interaction this deployment supports: a native
1669
- * deployment opens one OS chooser, a browse deployment serves a listing the page
1670
- * draws itself. Consumers are meant to switch on `capability().kind`.
1671
- *
1672
- * This plugin used to compile its own C# chooser and fall back to PowerShell. That
1673
- * was a reimplementation of something the host already ships, it could not follow a
1674
- * remote deployment, and it needed a compiler on the machine at first use.
1675
- *
1676
- * @returns `{ cancelled, path }` from a native chooser, else `{ browse: true }` or
1677
- * `{ unsupported: true }` so the page falls back to its own picker.
1678
- */
1679
- async function pickFolder(ctx) {
1680
- const picker = ctx !== null && ctx !== undefined && typeof ctx.get === 'function'
1681
- ? ctx.get('directoryPicker')
1682
- : undefined
1683
- if (picker === null || picker === undefined || typeof picker.capability !== 'function') {
1684
- return { unsupported: true }
1685
- }
1686
- let capability
1687
- try {
1688
- capability = picker.capability()
1689
- } catch {
1690
- return { unsupported: true }
1691
- }
1692
- if (capability === null || capability === undefined) return { unsupported: true }
1693
- if (capability.kind !== 'native' || typeof capability.pick !== 'function') return { browse: true }
1694
- // `pick(signal)` is mandatory: the host implementation begins with
1695
- // `if (signal.aborted) throw …`, so calling it bare throws a TypeError that
1696
- // reads like an unrelated failure ("… reading 'aborted'"). The timeout matches
1697
- // the one the previous PowerShell dialog used: a dialog nobody answers must not
1698
- // hold the request forever.
1699
- const controller = new AbortController()
1700
- const timer = setTimeout(() => controller.abort(), PICK_TIMEOUT_MS)
1701
- let picked
1702
- try {
1703
- picked = await capability.pick(controller.signal)
1704
- } finally {
1705
- clearTimeout(timer)
1706
- }
1707
- const chosen = typeof picked === 'string' && picked !== '' ? picked : null
1708
- if (chosen === null) return { cancelled: true, path: null }
1709
- const resolved = path.resolve(chosen)
1710
- let info
1711
- try {
1712
- info = await fsp.stat(resolved)
1713
- } catch {
1714
- throw new HttpError(400, 'invalid', '选中的目录已不存在')
1715
- }
1716
- if (!info.isDirectory()) throw new HttpError(400, 'invalid', '选中的不是目录')
1717
- return { cancelled: false, path: resolved }
1718
- }
1719
-
1720
-
1721
- // --- http --------------------------------------------------------------------
1722
-
1723
- function isLoopbackAddress(address) {
1724
- if (typeof address !== 'string' || address.length === 0) return false
1725
- return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1' || address.startsWith('127.')
1726
- }
1727
-
1728
- function isLocalHostHeader(host) {
1729
- if (typeof host !== 'string' || host.length === 0) return false
1730
- const name = host.split(':')[0].replace(/^\[|\]$/g, '').toLowerCase()
1731
- return name === 'localhost' || name === '127.0.0.1' || name === '::1'
1732
- }
1733
-
1734
- function sendJson(res, status, body) {
1735
- const payload = JSON.stringify(body)
1736
- res.writeHead(status, {
1737
- 'content-type': 'application/json; charset=utf-8',
1738
- 'content-length': Buffer.byteLength(payload),
1739
- })
1740
- res.end(payload)
1741
- }
1742
-
1743
- function readBody(req) {
1744
- return new Promise((resolve, reject) => {
1745
- let data = ''
1746
- req.on('data', (chunk) => {
1747
- data += chunk
1748
- if (data.length > 1e6) req.destroy()
1749
- })
1750
- req.on('end', () => resolve(data))
1751
- req.on('error', reject)
1752
- req.on('aborted', () => reject(new Error('aborted')))
1753
- })
1754
- }
1755
-
1756
- // Destructive local endpoint: loopback socket, loopback Host header, and a
1757
- // same-origin check when the browser sends Origin. Tunneled or LAN clients
1758
- // get 403 before any session data is touched.
1759
- function guard(req, res) {
1760
- if (!isLoopbackAddress(req.socket && req.socket.remoteAddress)) {
1761
- sendJson(res, 403, { ok: false, code: 'forbidden', error: 'loopback only' })
1762
- return false
1763
- }
1764
- const host = req.headers.host
1765
- if (!isLocalHostHeader(host)) {
1766
- sendJson(res, 403, { ok: false, code: 'forbidden', error: 'unexpected host' })
1767
- return false
1768
- }
1769
- const origin = req.headers.origin
1770
- if (typeof origin === 'string' && origin.length > 0) {
1771
- let originHost = null
1772
- try {
1773
- originHost = new URL(origin).host
1774
- } catch {
1775
- originHost = null
1776
- }
1777
- if (originHost !== host) {
1778
- sendJson(res, 403, { ok: false, code: 'forbidden', error: 'cross-origin request' })
1779
- return false
1780
- }
1781
- }
1782
- return true
1783
- }
1784
-
1785
- // --- plugin ------------------------------------------------------------------
1786
-
1787
- export function apply(ctx) {
1788
- warmCompiledHelpers()
1789
-
1790
- const registerRoutes = (webServer, fiber) => {
1791
- // Read-only scan: the dialog shows what a delete would move, before it does.
1792
- fiber.effect(() => webServer.register({
1793
- kind: 'exact',
1794
- path: `${ROUTE_PREFIX}/artifacts`,
1795
- handler: async (req, res) => {
1796
- if (!guard(req, res)) return
1797
- if (req.method !== 'POST') {
1798
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1799
- return
1800
- }
1801
- let body = {}
1802
- try {
1803
- const raw = await readBody(req)
1804
- if (raw) body = JSON.parse(raw)
1805
- } catch {
1806
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
1807
- return
1808
- }
1809
- const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
1810
- if (!sessionId) {
1811
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'sessionId required' })
1812
- return
1813
- }
1814
- try {
1815
- if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
1816
- const plan = await planArtifacts(ctx, sessionId, undefined, { skipGit: body.skipGit === true })
1817
- // A bad save path is reported alongside the plan rather than replacing
1818
- // it: the dialog can still show the files while saying where they cannot go.
1819
- const rootInfo = await resolveQuarantineRoot(body.root, plan.cwd)
1820
- sendJson(res, 200, {
1821
- ok: true,
1822
- sessionId,
1823
- ...plan,
1824
- defaultRoot: dshHome(),
1825
- quarantineRoot: rootInfo.error === undefined ? rootInfo.root : null,
1826
- rootError: rootInfo.error === undefined ? null : rootInfo.error,
1827
- })
1828
- } catch (error) {
1829
- const status = error instanceof HttpError ? error.status : 500
1830
- const code = error instanceof HttpError ? error.code : 'internal'
1831
- sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1832
- }
1833
- },
1834
- }))
1835
-
1836
- // Delete ONE produced file from the dialog. The path must be one the scan
1837
- // listed, so this cannot become a general-purpose delete primitive.
1838
- fiber.effect(() => webServer.register({
1839
- kind: 'exact',
1840
- path: `${ROUTE_PREFIX}/delete-file`,
1841
- handler: async (req, res) => {
1842
- if (!guard(req, res)) return
1843
- if (req.method !== 'POST') {
1844
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1845
- return
1846
- }
1847
- let body = {}
1848
- try {
1849
- const raw = await readBody(req)
1850
- if (raw) body = JSON.parse(raw)
1851
- } catch {
1852
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
1853
- return
1854
- }
1855
- const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
1856
- const target = typeof body.path === 'string' ? body.path.trim() : ''
1857
- try {
1858
- if (sessionId === '') throw new HttpError(400, 'invalid', 'sessionId required')
1859
- if (target === '') throw new HttpError(400, 'invalid', 'path required')
1860
- if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
1861
- const plan = await planArtifacts(ctx, sessionId, undefined, {})
1862
- const resolved = assertListedPath(plan, target)
1863
- const result = await removeOneFile(resolved, body.recycle === true)
1864
- sendJson(res, 200, { ok: true, ...result })
1865
- } catch (error) {
1866
- const status = error instanceof HttpError ? error.status : 500
1867
- const code = error instanceof HttpError ? error.code : 'internal'
1868
- sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1869
- }
1870
- },
1871
- }))
1872
-
1873
- // The real Windows folder dialog, raised on the user's behalf. Browsers cannot
1874
- // hand a page a filesystem path, but this process is local, so it can.
1875
- fiber.effect(() => webServer.register({
1876
- kind: 'exact',
1877
- path: `${ROUTE_PREFIX}/pick`,
1878
- handler: async (req, res) => {
1879
- if (!guard(req, res)) return
1880
- if (req.method !== 'POST') {
1881
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1882
- return
1883
- }
1884
- try {
1885
- const picked = await pickFolder(ctx)
1886
- if (picked.unsupported === true) {
1887
- sendJson(res, 200, { ok: false, code: 'unsupported', error: '宿主没有 directoryPicker 服务' })
1888
- return
1889
- }
1890
- if (picked.browse === true) {
1891
- sendJson(res, 200, { ok: false, code: 'browse', error: '浏览式宿主,请用页面内的选择器' })
1892
- return
1893
- }
1894
- sendJson(res, 200, { ok: true, ...picked })
1895
- } catch (error) {
1896
- const status = error instanceof HttpError ? error.status : 500
1897
- const code = error instanceof HttpError ? error.code : 'internal'
1898
- sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1899
- }
1900
- },
1901
- }))
1902
-
1903
- // Open a folder in the OS file manager. The path is validated as an existing
1904
- // directory first: this hands a string to Explorer, so it must never be able
1905
- // to carry anything but a directory.
1906
- fiber.effect(() => webServer.register({
1907
- kind: 'exact',
1908
- path: `${ROUTE_PREFIX}/reveal`,
1909
- handler: async (req, res) => {
1910
- if (!guard(req, res)) return
1911
- if (req.method !== 'POST') {
1912
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1913
- return
1914
- }
1915
- let body = {}
1916
- try {
1917
- const raw = await readBody(req)
1918
- if (raw) body = JSON.parse(raw)
1919
- } catch {
1920
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
1921
- return
1922
- }
1923
- try {
1924
- const target = typeof body.path === 'string' ? body.path.trim() : ''
1925
- if (target === '') throw new HttpError(400, 'invalid', 'path required')
1926
- const resolved = path.resolve(target)
1927
- let info
1928
- try {
1929
- info = await fsp.stat(resolved)
1930
- } catch {
1931
- throw new HttpError(400, 'invalid', '目录不存在')
1932
- }
1933
- if (!info.isDirectory()) throw new HttpError(400, 'invalid', '不是目录')
1934
- revealDirectory(resolved)
1935
- sendJson(res, 200, { ok: true, path: resolved })
1936
- } catch (error) {
1937
- const status = error instanceof HttpError ? error.status : 500
1938
- const code = error instanceof HttpError ? error.code : 'internal'
1939
- sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1940
- }
1941
- },
1942
- }))
1943
-
1944
- // Folder picker for the quarantine save path: directories only, never file
1945
- // contents, and the same loopback guard as every other route here.
1946
- fiber.effect(() => webServer.register({
1947
- kind: 'exact',
1948
- path: `${ROUTE_PREFIX}/browse`,
1949
- handler: async (req, res) => {
1950
- if (!guard(req, res)) return
1951
- if (req.method !== 'POST') {
1952
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1953
- return
1954
- }
1955
- let body = {}
1956
- try {
1957
- const raw = await readBody(req)
1958
- if (raw) body = JSON.parse(raw)
1959
- } catch {
1960
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
1961
- return
1962
- }
1963
- try {
1964
- const listing = await listDirectories(body.path)
1965
- sendJson(res, 200, { ok: true, ...listing })
1966
- } catch (error) {
1967
- const status = error instanceof HttpError ? error.status : 500
1968
- const code = error instanceof HttpError ? error.code : 'internal'
1969
- sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1970
- }
1971
- },
1972
- }))
1973
-
1974
- // The subagent sessions behind one conversation. A subagent is a session of
1975
- // its own, linked only by `parentSession`, so the dialog needs this list
1976
- // before it can offer anything to tick.
1977
- fiber.effect(() => webServer.register({
1978
- kind: 'exact',
1979
- path: `${ROUTE_PREFIX}/children`,
1980
- handler: async (req, res) => {
1981
- if (!guard(req, res)) return
1982
- if (req.method !== 'POST') {
1983
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1984
- return
1985
- }
1986
- let body = {}
1987
- try {
1988
- const raw = await readBody(req)
1989
- if (raw) body = JSON.parse(raw)
1990
- } catch {
1991
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
1992
- return
1993
- }
1994
- const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
1995
- if (!SESSION_ID_RE.test(sessionId)) {
1996
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'invalid session id' })
1997
- return
1998
- }
1999
- try {
2000
- const headers = await listSessionHeaders(ctx)
2001
- sendJson(res, 200, { ok: true, children: describeChildren(headers, sessionId) })
2002
- } catch (error) {
2003
- const status = error instanceof HttpError ? error.status : 500
2004
- const code = error instanceof HttpError ? error.code : 'internal'
2005
- sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2006
- }
2007
- },
2008
- }))
2009
- fiber.effect(() => webServer.register({
2010
- kind: 'exact',
2011
- path: `${ROUTE_PREFIX}/delete`,
2012
- handler: async (req, res) => {
2013
- if (!guard(req, res)) return
2014
- if (req.method !== 'POST') {
2015
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2016
- return
2017
- }
2018
- let body = {}
2019
- try {
2020
- const raw = await readBody(req)
2021
- if (raw) body = JSON.parse(raw)
2022
- } catch {
2023
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2024
- return
2025
- }
2026
- const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
2027
- if (!sessionId) {
2028
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'sessionId required' })
2029
- return
2030
- }
2031
- try {
2032
- // Validate before touching anything: the quarantine runs first, so an
2033
- // unchecked id would reach the filesystem ahead of deleteSession's own
2034
- // guard. `/artifacts` already validates at the same point.
2035
- if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
2036
- // Quarantine first: the session log is still there to derive the plan
2037
- // from, and a partial move leaves the conversation intact to retry.
2038
- const wantsQuarantine = typeof body.quarantine === 'object' && body.quarantine !== null
2039
- // The plan handed to the move must honour the same `skipGit` the dialog
2040
- // listed, or a file the listing refused to show would move anyway.
2041
- const plan = wantsQuarantine
2042
- ? await planArtifacts(ctx, sessionId, undefined, { skipGit: body.quarantine.skipGit === true })
2043
- : null
2044
- const quarantine = await runQuarantine(ctx, sessionId, body.quarantine, plan)
2045
- const result = await deleteSession(ctx, sessionId, {
2046
- recycle: body.recycle !== false,
2047
- childSessionIds: Array.isArray(body.childSessionIds) ? body.childSessionIds : [],
2048
- })
2049
- sendJson(res, 200, quarantine === null ? { ok: true, ...result } : { ok: true, ...result, quarantine })
2050
- } catch (error) {
2051
- const status = error instanceof HttpError ? error.status : 500
2052
- const code = error instanceof HttpError ? error.code : 'internal'
2053
- sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2054
- }
2055
- },
2056
- }))
2057
-
2058
- fiber.effect(() => webServer.register({
2059
- kind: 'exact',
2060
- path: `${ROUTE_PREFIX}/delete-many`,
2061
- handler: async (req, res) => {
2062
- if (!guard(req, res)) return
2063
- if (req.method !== 'POST') {
2064
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2065
- return
2066
- }
2067
- let body = {}
2068
- try {
2069
- const raw = await readBody(req)
2070
- if (raw) body = JSON.parse(raw)
2071
- } catch {
2072
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2073
- return
2074
- }
2075
- const sessionIds = Array.isArray(body.sessionIds)
2076
- ? [...new Set(body.sessionIds.filter((id) => typeof id === 'string' && id.trim()).map((id) => id.trim()))]
2077
- : []
2078
- if (sessionIds.length === 0) {
2079
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'sessionIds required' })
2080
- return
2081
- }
2082
- if (sessionIds.length > MAX_BATCH) {
2083
- sendJson(res, 400, { ok: false, code: 'invalid', error: `too many sessions (max ${MAX_BATCH})` })
2084
- return
2085
- }
2086
- // Bounded-concurrency batch: every item runs the same guarded pipeline
2087
- // (lease retry, directory sweep, workspace accounting); independent
2088
- // sessions run in parallel and the workspace accounting mutation is
2089
- // serialized inside deleteSession, so a batch can never interleave two
2090
- // deletions of the same storage.
2091
- const results = await runWithConcurrency(sessionIds, BATCH_CONCURRENCY, async (sessionId) => {
2092
- try {
2093
- const result = await deleteSession(ctx, sessionId, {
2094
- recycle: body.recycle !== false,
2095
- childSessionIds: Array.isArray(body.childSessionIds) ? body.childSessionIds : [],
2096
- })
2097
- return { sessionId, ok: true, removed: result.removed }
2098
- } catch (error) {
2099
- return {
2100
- sessionId,
2101
- ok: false,
2102
- code: error instanceof HttpError ? error.code : 'internal',
2103
- error: String((error && error.message) || error),
2104
- }
2105
- }
2106
- })
2107
- const deleted = results.filter((item) => item.ok).length
2108
- sendJson(res, 200, { ok: true, results, deleted, failed: results.length - deleted })
2109
- },
2110
- }))
2111
- }
2112
-
2113
- const webServer = ctx.get('webServer')
2114
- if (webServer) {
2115
- registerRoutes(webServer, ctx)
2116
- } else {
2117
- // A terminal-only profile never provides a web surface; register once one
2118
- // appears instead of waiting on a service that will never arrive.
2119
- ctx.inject(['webServer'], (sub) => registerRoutes(sub.webServer, sub))
2120
- }
2121
- }
2122
-
2123
- // Re-exported for the offline test suite, which drives the artifact plan and the
2124
- // quarantine against a scratch tree and a stubbed persistence service. Nothing
2125
- // else in the host reads this face.
2126
- export const internals = {
2127
- pickFolder,
2128
- artifactCandidates,
2129
- assertListedPath,
2130
- removeOneFile,
2131
- claimQuarantineDirectory,
2132
- classifyPaths,
2133
- collectSessionPaths,
2134
- MAX_SCANNED,
2135
- findSessionCaches,
2136
- freeDestination,
2137
- identityKey,
2138
- insidePath,
2139
- listDirectories,
2140
- moveToSessionTrash,
2141
- planArtifacts,
2142
- quarantineFiles,
2143
- resolveQuarantineRoot,
2144
- removeForever,
2145
- deleteSession,
2146
- retirePaths,
2147
- retireTargets,
2148
- listSessionHeaders,
2149
- collectOrphans,
2150
- collectDescendants,
2151
- bareSessionId,
2152
- describeChildren,
2153
- selectChildDeletes,
2154
- runQuarantine,
2155
- sendToRecycleBin,
2156
- toolTarget,
2157
- trashCommandFor,
2158
- warmCompiledHelpers,
2159
- }
1246
+ || createdPlan.allowed.length > MAX_LISTED
1247
+ || modifiedPlan.allowed.length > MAX_LISTED
1248
+ || refused.length > MAX_LISTED,
1249
+ warnings,
1250
+ }
1251
+ }
1252
+
1253
+ /**
1254
+ * Claim a quarantine directory under the DSH home. The name carries second
1255
+ * resolution only, so two deletes can land on the same name; an exclusive mkdir
1256
+ * (never `recursive: true`, which would happily reuse an existing tree) decides
1257
+ * the winner and the loser retries with a suffix. Two runs therefore can never
1258
+ * share a tree, which is what stops one run's file from overwriting another's.
1259
+ * @param home - resolved DSH home.
1260
+ * @returns the claimed directory, or undefined when none could be claimed.
1261
+ */
1262
+ async function claimQuarantineDirectory(home) {
1263
+ // A fresh home has no quarantine root yet; creating it is the only write this
1264
+ // side does outside the quarantine tree, and it keeps a missing home from
1265
+ // turning into a silent "cannot claim" on the very first delete.
1266
+ try {
1267
+ await fsp.mkdir(home, { recursive: true })
1268
+ } catch {
1269
+ return undefined
1270
+ }
1271
+ const base = `${QUARANTINE_PREFIX}-${new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)}`
1272
+ for (let attempt = 0; attempt < 1000; attempt += 1) {
1273
+ const candidate = path.join(home, attempt === 0 ? base : `${base}-${attempt}`)
1274
+ try {
1275
+ await fsp.mkdir(candidate, { recursive: false })
1276
+ return candidate
1277
+ } catch (error) {
1278
+ if (error && error.code === 'EEXIST') continue
1279
+ return undefined
1280
+ }
1281
+ }
1282
+ return undefined
1283
+ }
1284
+
1285
+ /** Whether a path exists, without throwing. */
1286
+ async function pathExists(target) {
1287
+ try {
1288
+ await fsp.access(target)
1289
+ return true
1290
+ } catch {
1291
+ return false
1292
+ }
1293
+ }
1294
+
1295
+ /**
1296
+ * A destination inside the quarantine tree that does not already exist. The
1297
+ * move itself must never overwrite: a quarantine that silently replaced an
1298
+ * earlier copy would destroy the only surviving copy of the file it replaced.
1299
+ * @param directory - claimed quarantine directory.
1300
+ * @param relative - path relative to the session's working directory.
1301
+ * @returns a free absolute path, or undefined when every name was taken.
1302
+ */
1303
+ async function freeDestination(directory, relative) {
1304
+ const first = path.join(directory, relative)
1305
+ if (!(await pathExists(first))) return first
1306
+ const dir = path.dirname(first)
1307
+ const ext = path.extname(first)
1308
+ const stem = path.basename(first, ext)
1309
+ for (let n = 1; n < 10000; n += 1) {
1310
+ const candidate = path.join(dir, `${stem}-${n}${ext}`)
1311
+ if (!(await pathExists(candidate))) return candidate
1312
+ }
1313
+ return undefined
1314
+ }
1315
+
1316
+ /**
1317
+ * Move the chosen files into a timestamped quarantine directory under the DSH
1318
+ * home, preserving each path relative to the session's working directory. Files
1319
+ * are moved, never removed, and an existing quarantine entry is never replaced,
1320
+ * so a wrong call is always recoverable by hand.
1321
+ *
1322
+ * Every step is asynchronous on purpose: a cross-device move copies, and a
1323
+ * synchronous copy inside the request handler would freeze the event loop, which
1324
+ * means every other session's traffic stalls behind one large quarantine.
1325
+ *
1326
+ * @param targets - absolute file paths to move.
1327
+ * @param cwd - the session's recorded working directory.
1328
+ * @param home - resolved DSH home.
1329
+ * @returns `{ directory, moved, failed }`.
1330
+ */
1331
+ async function quarantineFiles(targets, cwd, home) {
1332
+ const moved = []
1333
+ const failed = []
1334
+ if (targets.length === 0) return { directory: null, moved, failed }
1335
+
1336
+ const directory = await claimQuarantineDirectory(home)
1337
+ if (directory === undefined) {
1338
+ for (const target of targets) failed.push({ path: target, error: '无法创建隔离目录' })
1339
+ return { directory: null, moved, failed }
1340
+ }
1341
+
1342
+ let realCwd = cwd
1343
+ if (typeof cwd === 'string') {
1344
+ try {
1345
+ realCwd = await fsp.realpath(cwd)
1346
+ } catch {
1347
+ // keep the recorded spelling; classifyPaths already proved containment
1348
+ }
1349
+ }
1350
+ for (const target of targets) {
1351
+ let relative = path.basename(target)
1352
+ if (typeof realCwd === 'string') {
1353
+ const candidate = path.relative(realCwd, target)
1354
+ if (candidate !== '' && !candidate.startsWith('..') && !path.isAbsolute(candidate)) relative = candidate
1355
+ }
1356
+ try {
1357
+ await fsp.mkdir(path.dirname(path.join(directory, relative)), { recursive: true })
1358
+ const destination = await freeDestination(directory, relative)
1359
+ if (destination === undefined) {
1360
+ failed.push({ path: target, error: '隔离目录内没有可用的目标文件名' })
1361
+ continue
1362
+ }
1363
+ try {
1364
+ await fsp.rename(target, destination)
1365
+ } catch {
1366
+ // A cross-device rename fails; fall back to copy-then-remove. `COPYFILE_EXCL`
1367
+ // keeps the copy from replacing anything that appeared in between.
1368
+ await fsp.copyFile(target, destination, fs.constants.COPYFILE_EXCL)
1369
+ await fsp.rm(target, { force: true })
1370
+ }
1371
+ moved.push({ from: target, to: destination })
1372
+ } catch (error) {
1373
+ failed.push({ path: target, error: String((error && error.message) || error) })
1374
+ }
1375
+ }
1376
+ return { directory, moved, failed }
1377
+ }
1378
+
1379
+ /**
1380
+ * The files one plan actually offered. The per-file delete button sends back a
1381
+ * path from this list, and the route refuses anything else: a request cannot
1382
+ * name a file the user was never shown.
1383
+ *
1384
+ * @param plan - the artifact plan this plugin produced for a session.
1385
+ * @returns every listed path, created and modified alike.
1386
+ */
1387
+ function artifactCandidates(plan) {
1388
+ const out = []
1389
+ for (const group of [plan.created, plan.modified]) {
1390
+ if (!Array.isArray(group)) continue
1391
+ for (const row of group) {
1392
+ if (row !== null && row !== undefined && typeof row.path === 'string') out.push(row.path)
1393
+ }
1394
+ }
1395
+ return out
1396
+ }
1397
+
1398
+ /**
1399
+ * The path a per-file delete may touch: one the plan listed, nothing else.
1400
+ * Without this the button would be a general-purpose delete primitive reachable
1401
+ * from the page.
1402
+ *
1403
+ * @param plan - the artifact plan for the session.
1404
+ * @param target - the path the page asked for.
1405
+ * @returns the resolved path, ready to unlink.
1406
+ */
1407
+ function assertListedPath(plan, target) {
1408
+ const resolved = path.resolve(target)
1409
+ const listed = artifactCandidates(plan).some((candidate) => path.resolve(candidate) === resolved)
1410
+ if (!listed) throw new HttpError(403, 'not-listed', '该文件不在本对话的产出清单里')
1411
+ return resolved
1412
+ }
1413
+
1414
+ /**
1415
+ * Delete one produced file. The destination is the user's call, and the dialog
1416
+ * passes the same preference that governs a conversation delete: to the system
1417
+ * trash, or outright.
1418
+ *
1419
+ * @param target - absolute path of the file.
1420
+ * @param recycle - true to send it to the system recycle bin.
1421
+ * @returns `{ recycled }` describing where it went.
1422
+ */
1423
+ async function removeOneFile(target, recycle) {
1424
+ const resolved = path.resolve(target)
1425
+ let info
1426
+ try {
1427
+ info = await fsp.lstat(resolved)
1428
+ } catch (error) {
1429
+ throw new HttpError(404, 'missing', `文件已不存在:${String((error && error.message) || error)}`)
1430
+ }
1431
+ if (!info.isFile()) throw new HttpError(400, 'not-a-file', '只能删除普通文件')
1432
+ if (recycle === true) {
1433
+ const ok = await sendToRecycleBin([resolved])
1434
+ if (!ok) throw new HttpError(500, 'recycle', '移入回收站失败')
1435
+ return { recycled: true }
1436
+ }
1437
+ try {
1438
+ await fsp.unlink(resolved)
1439
+ } catch (error) {
1440
+ throw new HttpError(500, 'unlink', `删除失败:${String((error && error.message) || error)}`)
1441
+ }
1442
+ return { recycled: false }
1443
+ }
1444
+
1445
+ /**
1446
+ * Quarantine the files one request selected. The candidate set is recomputed
1447
+ * here from the session log and the request's paths are intersected with it, so
1448
+ * a tampered request cannot move anything the user was not shown.
1449
+ * @param ctx - host plugin context.
1450
+ * @param sessionId - validated session id.
1451
+ * @param request - `{ scope, paths }` from the client; undefined asks for none.
1452
+ * @returns the outcome, or null when the request asked for no quarantine.
1453
+ */
1454
+ async function runQuarantine(ctx, sessionId, request, knownPlan) {
1455
+ if (request === undefined || request === null || typeof request !== 'object') return null
1456
+ // Validated here as well as at the route, because `internals` exposes this
1457
+ // function and a direct caller must not be able to skip the check.
1458
+ if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
1459
+ const scope = request.scope === 'all' ? 'all' : 'created'
1460
+ // The same flag the dialog was built with, so a derived set cannot contain a
1461
+ // file the listing refused to show.
1462
+ const skipGit = request.skipGit === true
1463
+ // Re-deriving the plan is the expensive half of a delete; a caller that already
1464
+ // holds it for this session hands it over instead of paying for it twice.
1465
+ const plan = knownPlan === undefined || knownPlan === null
1466
+ ? await planArtifacts(ctx, sessionId, undefined, { skipGit })
1467
+ : knownPlan
1468
+ // A handed-in plan must be this session's plan. The route always derives it
1469
+ // from the same id, but `internals` exposes this function, and a future caller
1470
+ // passing its neighbour's plan would move files the user never saw.
1471
+ if (plan.sessionId !== sessionId) throw new HttpError(400, 'invalid', 'plan does not belong to this session')
1472
+ const candidates = scope === 'all' ? [...plan.created, ...plan.modified] : [...plan.created]
1473
+ const allowed = new Set(candidates.map((row) => row.path))
1474
+ const requested = Array.isArray(request.paths) ? request.paths : null
1475
+ const requestedStrings = requested === null ? null : new Set(requested.filter((value) => typeof value === 'string'))
1476
+ const targets = requested === null
1477
+ ? [...allowed]
1478
+ : [...requestedStrings].filter((value) => allowed.has(value))
1479
+ // Resolve the configured save path before moving a single file: a bad path must
1480
+ // stop the request, not send the files somewhere unintended.
1481
+ const rootInfo = await resolveQuarantineRoot(request.root, plan.cwd)
1482
+ if (rootInfo.error !== undefined) throw new HttpError(400, 'invalid', rootInfo.error)
1483
+ const root = rootInfo.root
1484
+ const outcome = await quarantineFiles(targets, plan.cwd, root)
1485
+ return {
1486
+ scope,
1487
+ directory: outcome.moved.length > 0 ? outcome.directory : null,
1488
+ root,
1489
+ moved: outcome.moved,
1490
+ failed: outcome.failed,
1491
+ candidates: allowed.size,
1492
+ selected: targets.length,
1493
+ dropped: requestedStrings === null ? 0 : requestedStrings.size - targets.length,
1494
+ }
1495
+ }
1496
+
1497
+ /**
1498
+ * Decide which directory the timestamped quarantine folder is created under. An
1499
+ * empty request means the DSH home, which is what every earlier version did.
1500
+ * @param requested - the directory the client asked for, if any.
1501
+ * @param cwd - the session's working directory, used to refuse a "quarantine"
1502
+ * that would only shuffle the files around inside the tree they came from.
1503
+ * @returns `{ root }` or `{ error }`.
1504
+ */
1505
+ async function resolveQuarantineRoot(requested, cwd) {
1506
+ const home = dshHome()
1507
+ if (requested === undefined || requested === null || requested === '') return { root: home }
1508
+ if (typeof requested !== 'string') return { error: '保存路径必须是字符串' }
1509
+ if (requested.length > 4096) return { error: '保存路径过长' }
1510
+ if (!path.isAbsolute(requested)) return { error: '保存路径必须是绝对路径' }
1511
+
1512
+ let real
1513
+ try {
1514
+ real = await fsp.realpath(requested)
1515
+ } catch {
1516
+ return { error: `保存路径不存在:${requested}` }
1517
+ }
1518
+ let info
1519
+ try {
1520
+ info = await fsp.stat(real)
1521
+ } catch {
1522
+ return { error: `无法读取保存路径:${requested}` }
1523
+ }
1524
+ if (!info.isDirectory()) return { error: '保存路径不是目录' }
1525
+
1526
+ // The sessions store belongs to DSH; filling it with quarantined files would
1527
+ // drop them back into the one tree the delete pipeline sweeps.
1528
+ const sessionsRoot = path.join(home, 'sessions')
1529
+ if (real === sessionsRoot || insidePath(sessionsRoot, real)) {
1530
+ return { error: '不能把隔离夹设在会话存储目录内' }
1531
+ }
1532
+ if (typeof cwd === 'string') {
1533
+ let realCwd
1534
+ try {
1535
+ realCwd = await fsp.realpath(cwd)
1536
+ } catch {
1537
+ realCwd = undefined
1538
+ }
1539
+ if (realCwd !== undefined && (real === realCwd || insidePath(realCwd, real))) {
1540
+ return { error: '不能把隔离夹设在会话工作目录内' }
1541
+ }
1542
+ }
1543
+ return { root: real }
1544
+ }
1545
+
1546
+ /** The drive letters Windows exposes, skipping the ones that cannot be read. */
1547
+ async function listDriveRoots() {
1548
+ if (process.platform !== 'win32') return []
1549
+ const roots = []
1550
+ for (let code = 65; code <= 90; code += 1) {
1551
+ const drive = `${String.fromCharCode(code)}:\\`
1552
+ try {
1553
+ await fsp.access(drive)
1554
+ roots.push({ name: drive, path: drive })
1555
+ } catch {
1556
+ // absent or unreadable: not offered
1557
+ }
1558
+ }
1559
+ return roots
1560
+ }
1561
+
1562
+ /**
1563
+ * One directory listing for the folder picker. Directories only: the picker
1564
+ * chooses where a folder is created, so files would be noise.
1565
+ * @param target - absolute directory to list; the DSH home when omitted.
1566
+ */
1567
+ async function listDirectories(target) {
1568
+ const home = dshHome()
1569
+ const start = target === undefined || target === null || target === '' ? home : target
1570
+ if (typeof start !== 'string') throw new HttpError(400, 'invalid', 'path must be a string')
1571
+ if (!path.isAbsolute(start)) throw new HttpError(400, 'invalid', 'path must be absolute')
1572
+
1573
+ let real
1574
+ try {
1575
+ real = await fsp.realpath(start)
1576
+ } catch {
1577
+ throw new HttpError(400, 'invalid', `目录不存在:${start}`)
1578
+ }
1579
+ let entries
1580
+ try {
1581
+ entries = await fsp.readdir(real, { withFileTypes: true })
1582
+ } catch (error) {
1583
+ throw new HttpError(400, 'invalid', `无法读取目录:${String((error && error.message) || error)}`)
1584
+ }
1585
+
1586
+ const directories = []
1587
+ for (const entry of entries) {
1588
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
1589
+ const full = path.join(real, entry.name)
1590
+ try {
1591
+ // `stat` follows a link, so a shortcut to a folder is still offered.
1592
+ const info = await fsp.stat(full)
1593
+ if (!info.isDirectory()) continue
1594
+ } catch {
1595
+ continue
1596
+ }
1597
+ directories.push({ name: entry.name, path: full })
1598
+ }
1599
+ directories.sort((a, b) => a.name.localeCompare(b.name))
1600
+
1601
+ const parent = real === path.parse(real).root ? null : path.dirname(real)
1602
+ return {
1603
+ path: real,
1604
+ parent,
1605
+ entries: directories.slice(0, MAX_BROWSE_ENTRIES),
1606
+ truncated: directories.length > MAX_BROWSE_ENTRIES,
1607
+ // At a drive root, offer the other drives so Windows users are not stranded.
1608
+ roots: parent === null ? await listDriveRoots() : [],
1609
+ defaultRoot: home,
1610
+ }
1611
+ }
1612
+
1613
+ /**
1614
+ * Run one PowerShell invocation and resolve its trimmed stdout.
1615
+ *
1616
+ * The script is passed as a file, never on stdin: `-Command -` reads stdin with
1617
+ * the console code page, and a non-ASCII byte in the script (the Chinese dialog
1618
+ * description, for one) silently killed the whole run instead of erroring.
1619
+ */
1620
+ function runPowershell(args, timeoutMs) {
1621
+ return new Promise((resolve, reject) => {
1622
+ const child = spawn('powershell.exe', args, {
1623
+ windowsHide: true,
1624
+ })
1625
+ let out = ''
1626
+ let err = ''
1627
+ let settled = false
1628
+ const finish = (fn, value) => {
1629
+ if (settled) return
1630
+ settled = true
1631
+ clearTimeout(timer)
1632
+ fn(value)
1633
+ }
1634
+ const timer = setTimeout(() => {
1635
+ try { child.kill() } catch { /* already gone */ }
1636
+ finish(reject, new HttpError(504, 'timeout', '等待系统对话框超时'))
1637
+ }, timeoutMs)
1638
+
1639
+ child.stdout.on('data', (chunk) => { out += chunk.toString('utf8') })
1640
+ child.stderr.on('data', (chunk) => { err += chunk.toString('utf8') })
1641
+ child.on('error', (error) => {
1642
+ finish(reject, new HttpError(500, 'spawn', `无法启动系统对话框:${String((error && error.message) || error)}`))
1643
+ })
1644
+ child.on('close', (code) => {
1645
+ if (code !== 0) {
1646
+ finish(reject, new HttpError(500, 'shell', `系统对话框异常退出(${code}):${err.trim().slice(0, 300)}`))
1647
+ return
1648
+ }
1649
+ finish(resolve, out.trim())
1650
+ })
1651
+ })
1652
+ }
1653
+
1654
+ /**
1655
+ * Open a directory in the operating system's file manager. The child is detached
1656
+ * and unreferenced so the HTTP response returns at once and the window lives on
1657
+ * its own; `explorer.exe` reports a non-zero exit even when it succeeds, so its
1658
+ * status is deliberately ignored.
1659
+ */
1660
+ function revealDirectory(directory) {
1661
+ const opener = process.platform === 'win32'
1662
+ ? { program: 'explorer.exe', args: [directory] }
1663
+ : process.platform === 'darwin'
1664
+ ? { program: 'open', args: [directory] }
1665
+ : { program: 'xdg-open', args: [directory] }
1666
+ const child = spawn(opener.program, opener.args, { detached: true, stdio: 'ignore', windowsHide: false })
1667
+ // Without this listener a failed spawn (explorer missing, blocked by security
1668
+ // software) surfaces as an unhandled `error` event and takes the host down.
1669
+ child.on('error', () => {})
1670
+ child.unref()
1671
+ }
1672
+
1673
+ /**
1674
+ * Ask the host for a directory.
1675
+ *
1676
+ * DSH mounts `ctx.directoryPicker` (`@deepseek-ai/dsh-host-directory-picker-auto`),
1677
+ * whose capability names the interaction this deployment supports: a native
1678
+ * deployment opens one OS chooser, a browse deployment serves a listing the page
1679
+ * draws itself. Consumers are meant to switch on `capability().kind`.
1680
+ *
1681
+ * This plugin used to compile its own C# chooser and fall back to PowerShell. That
1682
+ * was a reimplementation of something the host already ships, it could not follow a
1683
+ * remote deployment, and it needed a compiler on the machine at first use.
1684
+ *
1685
+ * @returns `{ cancelled, path }` from a native chooser, else `{ browse: true }` or
1686
+ * `{ unsupported: true }` so the page falls back to its own picker.
1687
+ */
1688
+ async function pickFolder(ctx) {
1689
+ const picker = ctx !== null && ctx !== undefined && typeof ctx.get === 'function'
1690
+ ? ctx.get('directoryPicker')
1691
+ : undefined
1692
+ if (picker === null || picker === undefined || typeof picker.capability !== 'function') {
1693
+ return { unsupported: true }
1694
+ }
1695
+ let capability
1696
+ try {
1697
+ capability = picker.capability()
1698
+ } catch {
1699
+ return { unsupported: true }
1700
+ }
1701
+ if (capability === null || capability === undefined) return { unsupported: true }
1702
+ if (capability.kind !== 'native' || typeof capability.pick !== 'function') return { browse: true }
1703
+ // `pick(signal)` is mandatory: the host implementation begins with
1704
+ // `if (signal.aborted) throw …`, so calling it bare throws a TypeError that
1705
+ // reads like an unrelated failure ("… reading 'aborted'"). The timeout matches
1706
+ // the one the previous PowerShell dialog used: a dialog nobody answers must not
1707
+ // hold the request forever.
1708
+ const controller = new AbortController()
1709
+ const timer = setTimeout(() => controller.abort(), PICK_TIMEOUT_MS)
1710
+ let picked
1711
+ try {
1712
+ picked = await capability.pick(controller.signal)
1713
+ } finally {
1714
+ clearTimeout(timer)
1715
+ }
1716
+ const chosen = typeof picked === 'string' && picked !== '' ? picked : null
1717
+ if (chosen === null) return { cancelled: true, path: null }
1718
+ const resolved = path.resolve(chosen)
1719
+ let info
1720
+ try {
1721
+ info = await fsp.stat(resolved)
1722
+ } catch {
1723
+ throw new HttpError(400, 'invalid', '选中的目录已不存在')
1724
+ }
1725
+ if (!info.isDirectory()) throw new HttpError(400, 'invalid', '选中的不是目录')
1726
+ return { cancelled: false, path: resolved }
1727
+ }
1728
+
1729
+
1730
+ // --- http --------------------------------------------------------------------
1731
+
1732
+ function isLoopbackAddress(address) {
1733
+ if (typeof address !== 'string' || address.length === 0) return false
1734
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1' || address.startsWith('127.')
1735
+ }
1736
+
1737
+ function isLocalHostHeader(host) {
1738
+ if (typeof host !== 'string' || host.length === 0) return false
1739
+ const name = host.split(':')[0].replace(/^\[|\]$/g, '').toLowerCase()
1740
+ return name === 'localhost' || name === '127.0.0.1' || name === '::1'
1741
+ }
1742
+
1743
+ function sendJson(res, status, body) {
1744
+ const payload = JSON.stringify(body)
1745
+ res.writeHead(status, {
1746
+ 'content-type': 'application/json; charset=utf-8',
1747
+ 'content-length': Buffer.byteLength(payload),
1748
+ })
1749
+ res.end(payload)
1750
+ }
1751
+
1752
+ function readBody(req) {
1753
+ return new Promise((resolve, reject) => {
1754
+ let data = ''
1755
+ req.on('data', (chunk) => {
1756
+ data += chunk
1757
+ if (data.length > 1e6) req.destroy()
1758
+ })
1759
+ req.on('end', () => resolve(data))
1760
+ req.on('error', reject)
1761
+ req.on('aborted', () => reject(new Error('aborted')))
1762
+ })
1763
+ }
1764
+
1765
+ // Destructive local endpoint: loopback socket, loopback Host header, and a
1766
+ // same-origin check when the browser sends Origin. Tunneled or LAN clients
1767
+ // get 403 before any session data is touched.
1768
+ function guard(req, res) {
1769
+ if (!isLoopbackAddress(req.socket && req.socket.remoteAddress)) {
1770
+ sendJson(res, 403, { ok: false, code: 'forbidden', error: 'loopback only' })
1771
+ return false
1772
+ }
1773
+ const host = req.headers.host
1774
+ if (!isLocalHostHeader(host)) {
1775
+ sendJson(res, 403, { ok: false, code: 'forbidden', error: 'unexpected host' })
1776
+ return false
1777
+ }
1778
+ const origin = req.headers.origin
1779
+ if (typeof origin === 'string' && origin.length > 0) {
1780
+ let originHost = null
1781
+ try {
1782
+ originHost = new URL(origin).host
1783
+ } catch {
1784
+ originHost = null
1785
+ }
1786
+ if (originHost !== host) {
1787
+ sendJson(res, 403, { ok: false, code: 'forbidden', error: 'cross-origin request' })
1788
+ return false
1789
+ }
1790
+ }
1791
+ return true
1792
+ }
1793
+
1794
+ // --- plugin ------------------------------------------------------------------
1795
+
1796
+ export function apply(ctx) {
1797
+ warmCompiledHelpers()
1798
+
1799
+ const registerRoutes = (webServer, fiber) => {
1800
+ // Read-only scan: the dialog shows what a delete would move, before it does.
1801
+ fiber.effect(() => webServer.register({
1802
+ kind: 'exact',
1803
+ path: `${ROUTE_PREFIX}/artifacts`,
1804
+ handler: async (req, res) => {
1805
+ if (!guard(req, res)) return
1806
+ if (req.method !== 'POST') {
1807
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1808
+ return
1809
+ }
1810
+ let body = {}
1811
+ try {
1812
+ const raw = await readBody(req)
1813
+ if (raw) body = JSON.parse(raw)
1814
+ } catch {
1815
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
1816
+ return
1817
+ }
1818
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
1819
+ if (!sessionId) {
1820
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'sessionId required' })
1821
+ return
1822
+ }
1823
+ try {
1824
+ if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
1825
+ const plan = await planArtifacts(ctx, sessionId, undefined, { skipGit: body.skipGit === true })
1826
+ // A bad save path is reported alongside the plan rather than replacing
1827
+ // it: the dialog can still show the files while saying where they cannot go.
1828
+ const rootInfo = await resolveQuarantineRoot(body.root, plan.cwd)
1829
+ sendJson(res, 200, {
1830
+ ok: true,
1831
+ sessionId,
1832
+ ...plan,
1833
+ defaultRoot: dshHome(),
1834
+ quarantineRoot: rootInfo.error === undefined ? rootInfo.root : null,
1835
+ rootError: rootInfo.error === undefined ? null : rootInfo.error,
1836
+ })
1837
+ } catch (error) {
1838
+ const status = error instanceof HttpError ? error.status : 500
1839
+ const code = error instanceof HttpError ? error.code : 'internal'
1840
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1841
+ }
1842
+ },
1843
+ }))
1844
+
1845
+ // Delete ONE produced file from the dialog. The path must be one the scan
1846
+ // listed, so this cannot become a general-purpose delete primitive.
1847
+ fiber.effect(() => webServer.register({
1848
+ kind: 'exact',
1849
+ path: `${ROUTE_PREFIX}/delete-file`,
1850
+ handler: async (req, res) => {
1851
+ if (!guard(req, res)) return
1852
+ if (req.method !== 'POST') {
1853
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1854
+ return
1855
+ }
1856
+ let body = {}
1857
+ try {
1858
+ const raw = await readBody(req)
1859
+ if (raw) body = JSON.parse(raw)
1860
+ } catch {
1861
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
1862
+ return
1863
+ }
1864
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
1865
+ const target = typeof body.path === 'string' ? body.path.trim() : ''
1866
+ try {
1867
+ if (sessionId === '') throw new HttpError(400, 'invalid', 'sessionId required')
1868
+ if (target === '') throw new HttpError(400, 'invalid', 'path required')
1869
+ if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
1870
+ const plan = await planArtifacts(ctx, sessionId, undefined, {})
1871
+ const resolved = assertListedPath(plan, target)
1872
+ const result = await removeOneFile(resolved, body.recycle === true)
1873
+ sendJson(res, 200, { ok: true, ...result })
1874
+ } catch (error) {
1875
+ const status = error instanceof HttpError ? error.status : 500
1876
+ const code = error instanceof HttpError ? error.code : 'internal'
1877
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1878
+ }
1879
+ },
1880
+ }))
1881
+
1882
+ // The real Windows folder dialog, raised on the user's behalf. Browsers cannot
1883
+ // hand a page a filesystem path, but this process is local, so it can.
1884
+ fiber.effect(() => webServer.register({
1885
+ kind: 'exact',
1886
+ path: `${ROUTE_PREFIX}/pick`,
1887
+ handler: async (req, res) => {
1888
+ if (!guard(req, res)) return
1889
+ if (req.method !== 'POST') {
1890
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1891
+ return
1892
+ }
1893
+ try {
1894
+ const picked = await pickFolder(ctx)
1895
+ if (picked.unsupported === true) {
1896
+ sendJson(res, 200, { ok: false, code: 'unsupported', error: '宿主没有 directoryPicker 服务' })
1897
+ return
1898
+ }
1899
+ if (picked.browse === true) {
1900
+ sendJson(res, 200, { ok: false, code: 'browse', error: '浏览式宿主,请用页面内的选择器' })
1901
+ return
1902
+ }
1903
+ sendJson(res, 200, { ok: true, ...picked })
1904
+ } catch (error) {
1905
+ const status = error instanceof HttpError ? error.status : 500
1906
+ const code = error instanceof HttpError ? error.code : 'internal'
1907
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1908
+ }
1909
+ },
1910
+ }))
1911
+
1912
+ // Open a folder in the OS file manager. The path is validated as an existing
1913
+ // directory first: this hands a string to Explorer, so it must never be able
1914
+ // to carry anything but a directory.
1915
+ fiber.effect(() => webServer.register({
1916
+ kind: 'exact',
1917
+ path: `${ROUTE_PREFIX}/reveal`,
1918
+ handler: async (req, res) => {
1919
+ if (!guard(req, res)) return
1920
+ if (req.method !== 'POST') {
1921
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1922
+ return
1923
+ }
1924
+ let body = {}
1925
+ try {
1926
+ const raw = await readBody(req)
1927
+ if (raw) body = JSON.parse(raw)
1928
+ } catch {
1929
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
1930
+ return
1931
+ }
1932
+ try {
1933
+ const target = typeof body.path === 'string' ? body.path.trim() : ''
1934
+ if (target === '') throw new HttpError(400, 'invalid', 'path required')
1935
+ const resolved = path.resolve(target)
1936
+ let info
1937
+ try {
1938
+ info = await fsp.stat(resolved)
1939
+ } catch {
1940
+ throw new HttpError(400, 'invalid', '目录不存在')
1941
+ }
1942
+ if (!info.isDirectory()) throw new HttpError(400, 'invalid', '不是目录')
1943
+ revealDirectory(resolved)
1944
+ sendJson(res, 200, { ok: true, path: resolved })
1945
+ } catch (error) {
1946
+ const status = error instanceof HttpError ? error.status : 500
1947
+ const code = error instanceof HttpError ? error.code : 'internal'
1948
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1949
+ }
1950
+ },
1951
+ }))
1952
+
1953
+ // Folder picker for the quarantine save path: directories only, never file
1954
+ // contents, and the same loopback guard as every other route here.
1955
+ fiber.effect(() => webServer.register({
1956
+ kind: 'exact',
1957
+ path: `${ROUTE_PREFIX}/browse`,
1958
+ handler: async (req, res) => {
1959
+ if (!guard(req, res)) return
1960
+ if (req.method !== 'POST') {
1961
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1962
+ return
1963
+ }
1964
+ let body = {}
1965
+ try {
1966
+ const raw = await readBody(req)
1967
+ if (raw) body = JSON.parse(raw)
1968
+ } catch {
1969
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
1970
+ return
1971
+ }
1972
+ try {
1973
+ const listing = await listDirectories(body.path)
1974
+ sendJson(res, 200, { ok: true, ...listing })
1975
+ } catch (error) {
1976
+ const status = error instanceof HttpError ? error.status : 500
1977
+ const code = error instanceof HttpError ? error.code : 'internal'
1978
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1979
+ }
1980
+ },
1981
+ }))
1982
+
1983
+ // The subagent sessions behind one conversation. A subagent is a session of
1984
+ // its own, linked only by `parentSession`, so the dialog needs this list
1985
+ // before it can offer anything to tick.
1986
+ fiber.effect(() => webServer.register({
1987
+ kind: 'exact',
1988
+ path: `${ROUTE_PREFIX}/children`,
1989
+ handler: async (req, res) => {
1990
+ if (!guard(req, res)) return
1991
+ if (req.method !== 'POST') {
1992
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1993
+ return
1994
+ }
1995
+ let body = {}
1996
+ try {
1997
+ const raw = await readBody(req)
1998
+ if (raw) body = JSON.parse(raw)
1999
+ } catch {
2000
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2001
+ return
2002
+ }
2003
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
2004
+ if (!SESSION_ID_RE.test(sessionId)) {
2005
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'invalid session id' })
2006
+ return
2007
+ }
2008
+ try {
2009
+ const headers = await listSessionHeaders(ctx)
2010
+ sendJson(res, 200, { ok: true, children: describeChildren(headers, sessionId) })
2011
+ } catch (error) {
2012
+ const status = error instanceof HttpError ? error.status : 500
2013
+ const code = error instanceof HttpError ? error.code : 'internal'
2014
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2015
+ }
2016
+ },
2017
+ }))
2018
+ fiber.effect(() => webServer.register({
2019
+ kind: 'exact',
2020
+ path: `${ROUTE_PREFIX}/delete`,
2021
+ handler: async (req, res) => {
2022
+ if (!guard(req, res)) return
2023
+ if (req.method !== 'POST') {
2024
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2025
+ return
2026
+ }
2027
+ let body = {}
2028
+ try {
2029
+ const raw = await readBody(req)
2030
+ if (raw) body = JSON.parse(raw)
2031
+ } catch {
2032
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2033
+ return
2034
+ }
2035
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
2036
+ if (!sessionId) {
2037
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'sessionId required' })
2038
+ return
2039
+ }
2040
+ try {
2041
+ // Validate before touching anything: the quarantine runs first, so an
2042
+ // unchecked id would reach the filesystem ahead of deleteSession's own
2043
+ // guard. `/artifacts` already validates at the same point.
2044
+ if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
2045
+ // Quarantine first: the session log is still there to derive the plan
2046
+ // from, and a partial move leaves the conversation intact to retry.
2047
+ const wantsQuarantine = typeof body.quarantine === 'object' && body.quarantine !== null
2048
+ // The plan handed to the move must honour the same `skipGit` the dialog
2049
+ // listed, or a file the listing refused to show would move anyway.
2050
+ const plan = wantsQuarantine
2051
+ ? await planArtifacts(ctx, sessionId, undefined, { skipGit: body.quarantine.skipGit === true })
2052
+ : null
2053
+ const quarantine = await runQuarantine(ctx, sessionId, body.quarantine, plan)
2054
+ const result = await deleteSession(ctx, sessionId, {
2055
+ recycle: body.recycle !== false,
2056
+ childSessionIds: Array.isArray(body.childSessionIds) ? body.childSessionIds : [],
2057
+ })
2058
+ sendJson(res, 200, quarantine === null ? { ok: true, ...result } : { ok: true, ...result, quarantine })
2059
+ } catch (error) {
2060
+ const status = error instanceof HttpError ? error.status : 500
2061
+ const code = error instanceof HttpError ? error.code : 'internal'
2062
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2063
+ }
2064
+ },
2065
+ }))
2066
+
2067
+ fiber.effect(() => webServer.register({
2068
+ kind: 'exact',
2069
+ path: `${ROUTE_PREFIX}/delete-many`,
2070
+ handler: async (req, res) => {
2071
+ if (!guard(req, res)) return
2072
+ if (req.method !== 'POST') {
2073
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2074
+ return
2075
+ }
2076
+ let body = {}
2077
+ try {
2078
+ const raw = await readBody(req)
2079
+ if (raw) body = JSON.parse(raw)
2080
+ } catch {
2081
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2082
+ return
2083
+ }
2084
+ const sessionIds = Array.isArray(body.sessionIds)
2085
+ ? [...new Set(body.sessionIds.filter((id) => typeof id === 'string' && id.trim()).map((id) => id.trim()))]
2086
+ : []
2087
+ if (sessionIds.length === 0) {
2088
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'sessionIds required' })
2089
+ return
2090
+ }
2091
+ if (sessionIds.length > MAX_BATCH) {
2092
+ sendJson(res, 400, { ok: false, code: 'invalid', error: `too many sessions (max ${MAX_BATCH})` })
2093
+ return
2094
+ }
2095
+ // Bounded-concurrency batch: every item runs the same guarded pipeline
2096
+ // (lease retry, directory sweep, workspace accounting); independent
2097
+ // sessions run in parallel and the workspace accounting mutation is
2098
+ // serialized inside deleteSession, so a batch can never interleave two
2099
+ // deletions of the same storage.
2100
+ const results = await runWithConcurrency(sessionIds, BATCH_CONCURRENCY, async (sessionId) => {
2101
+ try {
2102
+ const result = await deleteSession(ctx, sessionId, {
2103
+ recycle: body.recycle !== false,
2104
+ childSessionIds: Array.isArray(body.childSessionIds) ? body.childSessionIds : [],
2105
+ })
2106
+ return { sessionId, ok: true, removed: result.removed }
2107
+ } catch (error) {
2108
+ return {
2109
+ sessionId,
2110
+ ok: false,
2111
+ code: error instanceof HttpError ? error.code : 'internal',
2112
+ error: String((error && error.message) || error),
2113
+ }
2114
+ }
2115
+ })
2116
+ const deleted = results.filter((item) => item.ok).length
2117
+ sendJson(res, 200, { ok: true, results, deleted, failed: results.length - deleted })
2118
+ },
2119
+ }))
2120
+ }
2121
+
2122
+ const webServer = ctx.get('webServer')
2123
+ if (webServer) {
2124
+ registerRoutes(webServer, ctx)
2125
+ } else {
2126
+ // A terminal-only profile never provides a web surface; register once one
2127
+ // appears instead of waiting on a service that will never arrive.
2128
+ ctx.inject(['webServer'], (sub) => registerRoutes(sub.webServer, sub))
2129
+ }
2130
+ }
2131
+
2132
+ // Re-exported for the offline test suite, which drives the artifact plan and the
2133
+ // quarantine against a scratch tree and a stubbed persistence service. Nothing
2134
+ // else in the host reads this face.
2135
+ export const internals = {
2136
+ pickFolder,
2137
+ artifactCandidates,
2138
+ assertListedPath,
2139
+ removeOneFile,
2140
+ claimQuarantineDirectory,
2141
+ classifyPaths,
2142
+ collectSessionPaths,
2143
+ MAX_SCANNED,
2144
+ findSessionCaches,
2145
+ freeDestination,
2146
+ identityKey,
2147
+ insidePath,
2148
+ listDirectories,
2149
+ moveToSessionTrash,
2150
+ planArtifacts,
2151
+ quarantineFiles,
2152
+ resolveQuarantineRoot,
2153
+ removeForever,
2154
+ deleteSession,
2155
+ retirePaths,
2156
+ retireTargets,
2157
+ listSessionHeaders,
2158
+ collectOrphans,
2159
+ collectDescendants,
2160
+ bareSessionId,
2161
+ describeChildren,
2162
+ selectChildDeletes,
2163
+ runQuarantine,
2164
+ sendToRecycleBin,
2165
+ toolTarget,
2166
+ trashCommandFor,
2167
+ warmCompiledHelpers,
2168
+ }