dsh-delete-session 0.5.0 → 0.5.3

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,2274 +1,2274 @@
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
- // A live session is the common case: detaching releases the write lease through
642
- // an asynchronous retirement, so the FIRST probe almost always finds it busy.
643
- // A flat 200ms delay therefore charged every live delete ~200ms before it even
644
- // started. The wait is now exponential — 20, 40, 80, 160, then the old 200ms —
645
- // which lands the typical case in ~20-40ms and keeps the ceiling unchanged
646
- // (total wait is shorter than 12 x 200ms, never longer).
647
- const BUSY_RETRY_ATTEMPTS = 12
648
- const BUSY_RETRY_BASE_MS = 20
649
- const BUSY_RETRY_MAX_MS = 200
650
-
651
- /**
652
- * How long to wait before retry `attempt` (1-based).
653
- * @param attempt - the retry about to happen.
654
- * @returns milliseconds to sleep.
655
- */
656
- function busyBackoff(attempt) {
657
- const step = BUSY_RETRY_BASE_MS * 2 ** Math.max(0, attempt - 1)
658
- return Math.min(step, BUSY_RETRY_MAX_MS)
659
- }
660
-
661
- function sleep(ms) {
662
- return new Promise((resolve) => setTimeout(resolve, ms))
663
- }
664
-
665
- async function assertNoActiveWriter(ctx, sessionId) {
666
- const sp = ctx.get('sessionPersistence')
667
- if (!sp || typeof sp.open !== 'function') return false
668
- for (let attempt = 1; attempt <= BUSY_RETRY_ATTEMPTS; attempt += 1) {
669
- let handle = null
670
- let busy = false
671
- try {
672
- handle = await sp.open(sessionId, 'write')
673
- } catch (error) {
674
- const message = String((error && error.message) || error)
675
- if (/own|busy|lock|hold|writer/i.test(message)) {
676
- busy = true
677
- } else {
678
- return false
679
- }
680
- } finally {
681
- try {
682
- if (handle && typeof handle.close === 'function') await handle.close()
683
- } catch {
684
- // lease release failure is harmless: the directory is removed next
685
- }
686
- }
687
- if (!busy) return true
688
- if (attempt < BUSY_RETRY_ATTEMPTS) await sleep(busyBackoff(attempt))
689
- }
690
- throw new HttpError(409, 'busy', 'session is currently open in DSH')
691
- }
692
-
693
- // Bounded concurrency for batch deletes. Different sessions are independent
694
- // (agent quiesce, lease probe and directory sweep all key off the session id),
695
- // so the pipeline runs in parallel through a small pool. The one shared
696
- // mutation - workspace accounting - is serialized through withWorkspaceLock so
697
- // two deletions can never interleave on the same store.
698
- //
699
- // 6 is measured, not guessed: on 64 sessions of ~2MB the wall time was
700
- // 281ms at 4, 189ms at 6 and 142ms at 8 (the I/O parallelism saturates around
701
- // 8), so 6 keeps a ~33% gain over 4 while staying below the saturation knee
702
- // and limiting the number of simultaneous lease-probe loops.
703
- const BATCH_CONCURRENCY = 6
704
- // The lease probe is a few milliseconds of waiting, not I/O: it can run wider
705
- // than the file sweep without adding load, and that width is the whole point of
706
- // phase 2 of the batch pipeline.
707
- const BATCH_PROBE_CONCURRENCY = 16
708
-
709
- let workspaceLock = Promise.resolve()
710
- function withWorkspaceLock(fn) {
711
- const run = workspaceLock.then(fn, fn)
712
- workspaceLock = run.then(() => undefined, () => undefined)
713
- return run
714
- }
715
-
716
- async function runWithConcurrency(items, limit, worker) {
717
- const results = new Array(items.length)
718
- let cursor = 0
719
- const runners = []
720
- for (let i = 0; i < Math.min(limit, items.length); i += 1) {
721
- runners.push((async () => {
722
- while (true) {
723
- const index = cursor
724
- cursor += 1
725
- if (index >= items.length) return
726
- results[index] = await worker(items[index], index)
727
- }
728
- })())
729
- }
730
- await Promise.all(runners)
731
- return results
732
- }
733
-
734
- async function detachFromWorkspace(ctx, sessionId) {
735
- const workspace = ctx.get('workspaceRegistry')
736
- if (!workspace) return false
737
- const variants = idVariants(sessionId)
738
- let touched = false
739
- try {
740
- if (typeof workspace.list === 'function') {
741
- for (const entry of workspace.list()) {
742
- if (!entry || !Array.isArray(entry.sessionIds)) continue
743
- if (!variants.some((variant) => entry.sessionIds.includes(variant))) continue
744
- try {
745
- await entry.detachSession(sessionId)
746
- touched = true
747
- } catch {
748
- // keep going: the header index cleanup below still applies
749
- }
750
- }
751
- }
752
- } catch {
753
- // registry unavailable
754
- }
755
- try {
756
- if (workspace.sessionPaths && typeof workspace.sessionPaths.delete === 'function') {
757
- for (const variant of variants) workspace.sessionPaths.delete(variant)
758
- }
759
- } catch {
760
- // private map absent on this version
761
- }
762
- try {
763
- if (workspace.headers && typeof workspace.headers.delete === 'function') {
764
- for (const variant of variants) workspace.headers.delete(variant)
765
- }
766
- } catch {
767
- // private map absent on this version
768
- }
769
- return touched
770
- }
771
-
772
- // --- core delete -------------------------------------------------------------
773
-
774
- /**
775
- * Phase 1 - stop everything that writes to a session and flush its log.
776
- * Cheap and independent per session, so a batch runs these together.
777
- */
778
- async function stopSession(ctx, sessionId) {
779
- await quiesceAgent(ctx, sessionId)
780
- return flushAndDetach(ctx, sessionId)
781
- }
782
-
783
- /** Phase 2 - wait for the write lease. The waits of different sessions overlap. */
784
- async function requireWritable(ctx, sessionId) {
785
- await assertNoActiveWriter(ctx, sessionId)
786
- }
787
-
788
- /**
789
- * Phase 3 - retire the files, verify, drop the workspace accounting, then take
790
- * the ticked child sessions with it.
791
- *
792
- * Children stay sequential and last: one failure never takes the parent result
793
- * down with it, because the parent is what the user clicked.
794
- *
795
- * @returns `{ removed, caches, workspaceDetached, children }`.
796
- */
797
- async function retireSession(ctx, sessionId, options, stopResult) {
798
- const recycle = options === undefined || options === null || options.recycle !== false
799
- const childSessionIds = options !== undefined && options !== null && Array.isArray(options.childSessionIds)
800
- ? options.childSessionIds
801
- .filter((id) => typeof id === 'string' && SESSION_ID_RE.test(id))
802
- .filter((id) => bareSessionId(id) !== bareSessionId(sessionId))
803
- : []
804
- const flushed = stopResult !== undefined && stopResult !== null && stopResult.flushed === true
805
- const detached = stopResult !== undefined && stopResult !== null && stopResult.detached === true
806
-
807
- const { removed, caches } = await retireSessionFiles(sessionId, recycle)
808
-
809
- const sp = ctx.get('sessionPersistence')
810
- if (sp && typeof sp.stat === 'function') {
811
- const after = await sp.stat(sessionId).catch(() => undefined)
812
- if (after) {
813
- throw new HttpError(500, 'verify-failed', 'session is still visible to the persistence service after deletion')
814
- }
815
- }
816
- const leftover = findSessionDirs(sessionId)
817
- if (leftover.length > 0) {
818
- throw new HttpError(500, 'verify-failed', 'session directories could not be fully removed')
819
- }
820
-
821
- const workspaceDetached = await withWorkspaceLock(() => detachFromWorkspace(ctx, sessionId))
822
- if (removed === 0 && !workspaceDetached && !flushed && !detached && caches === 0) {
823
- throw new HttpError(404, 'not-found', 'session not found')
824
- }
825
-
826
- const children = []
827
- for (const childId of childSessionIds) {
828
- try {
829
- // A subagent can still be running while its parent is deleted. Removing the
830
- // log out from under it is what made the agent's next write fail with ENOENT,
831
- // so a child gets the same guard as the parent: stop it, flush it, and wait
832
- // for the write lease before a single byte moves.
833
- await quiesceAgent(ctx, childId)
834
- await flushAndDetach(ctx, childId)
835
- await assertNoActiveWriter(ctx, childId)
836
- const childFiles = await retireSessionFiles(childId, recycle)
837
- await withWorkspaceLock(() => detachFromWorkspace(ctx, childId))
838
- children.push({ id: childId, removed: childFiles.removed, caches: childFiles.caches })
839
- } catch (error) {
840
- // Never delete a child that could not be quieted: something is still writing
841
- // to it. Report it so the caller can try again once it settles.
842
- const busy = error instanceof HttpError && error.code === 'busy'
843
- children.push({
844
- id: childId,
845
- removed: 0,
846
- caches: 0,
847
- skipped: busy ? 'busy' : 'error',
848
- error: String((error && error.message) || error),
849
- })
850
- }
851
- }
852
-
853
- return { removed, caches, workspaceDetached, children }
854
- }
855
-
856
- /**
857
- * Delete one session: the three phases in order. Kept as the single-session
858
- * entry point, and expressed in the same phase helpers the batch uses so the two
859
- * can never drift apart.
860
- */
861
- async function deleteSession(ctx, sessionId, options) {
862
- if (!SESSION_ID_RE.test(sessionId)) {
863
- throw new HttpError(400, 'invalid', 'invalid session id')
864
- }
865
- const stopResult = await stopSession(ctx, sessionId)
866
- await requireWritable(ctx, sessionId)
867
- const result = await retireSession(ctx, sessionId, options, stopResult)
868
- return {
869
- removed: result.removed,
870
- caches: result.caches,
871
- stopped: stopResult !== undefined && stopResult.flushed !== undefined,
872
- flushed: stopResult.flushed,
873
- detached: stopResult.detached,
874
- workspaceDetached: result.workspaceDetached,
875
- children: result.children,
876
- }
877
- }
878
-
879
- /**
880
- * Delete many sessions as three overlapping phases:
881
- *
882
- * 1. stop and flush every session (bounded, but the work is tiny)
883
- * 2. probe every write lease (wide: these are the 20-40ms waits, and they only
884
- * overlap if nothing queues behind the retire workers)
885
- * 3. retire files, verify, detach accounting, take children (bounded)
886
- *
887
- * The old shape ran all three phases inside each session, six at a time, so a
888
- * batch of live sessions paid its lease waits in waves. One failing session never
889
- * takes the batch down: it comes back as `{ ok: false }`.
890
- *
891
- * @returns one `{ sessionId, ok, removed }` (or `{ ok: false, code, error }`) per id.
892
- */
893
- async function deleteSessions(ctx, sessionIds, options) {
894
- const valid = []
895
- const rejected = []
896
- for (const sessionId of sessionIds) {
897
- if (SESSION_ID_RE.test(sessionId)) valid.push(sessionId)
898
- else rejected.push({ sessionId, ok: false, code: 'invalid', error: 'invalid session id' })
899
- }
900
-
901
- // Phase 1: stop + flush. A failure here is that session's failure only.
902
- const stopped = new Map()
903
- const stopErrors = new Map()
904
- await runWithConcurrency(valid, BATCH_CONCURRENCY, async (sessionId) => {
905
- try {
906
- stopped.set(sessionId, await stopSession(ctx, sessionId))
907
- } catch (error) {
908
- stopErrors.set(sessionId, error)
909
- }
910
- })
911
-
912
- // Phase 2: lease probe, wide. Sessions that never stopped are not probed.
913
- const unready = new Map()
914
- const ready = valid.filter((sessionId) => !stopErrors.has(sessionId))
915
- await runWithConcurrency(ready, BATCH_PROBE_CONCURRENCY, async (sessionId) => {
916
- try {
917
- await requireWritable(ctx, sessionId)
918
- } catch (error) {
919
- unready.set(sessionId, error)
920
- }
921
- })
922
-
923
- // Phase 3: retire what is clear to go.
924
- const results = []
925
- const swept = valid.filter((sessionId) => !stopErrors.has(sessionId) && !unready.has(sessionId))
926
- const retired = new Map()
927
- const retireErrors = new Map()
928
- await runWithConcurrency(swept, BATCH_CONCURRENCY, async (sessionId) => {
929
- try {
930
- retired.set(sessionId, await retireSession(ctx, sessionId, options, stopped.get(sessionId)))
931
- } catch (error) {
932
- retireErrors.set(sessionId, error)
933
- }
934
- })
935
-
936
- for (const sessionId of valid) {
937
- const error = stopErrors.get(sessionId) || unready.get(sessionId) || retireErrors.get(sessionId)
938
- if (error !== undefined) {
939
- results.push({
940
- sessionId,
941
- ok: false,
942
- code: error instanceof HttpError ? error.code : 'internal',
943
- error: String((error && error.message) || error),
944
- })
945
- continue
946
- }
947
- results.push({ sessionId, ok: true, removed: retired.get(sessionId).removed })
948
- }
949
-
950
- return [...results, ...rejected]
951
- }
952
- /**
953
- * Take one session off the disk: its directories and its cache rows, then any
954
- * directory the drain recreated. Shared by the parent and every child, so a
955
- * subagent is retired exactly like the conversation the user clicked.
956
- *
957
- * @returns how many paths went away, and how many cache rows are now gone.
958
- */
959
- async function retireSessionFiles(sessionId, recycle) {
960
- const cacheFiles = findSessionCaches(sessionId)
961
- const targets = [...findSessionDirs(sessionId), ...cacheFiles]
962
- let gone = await retireTargets(targets, recycle)
963
- await new Promise((resolve) => setImmediate(resolve))
964
- gone = gone.concat(await retireTargets(findSessionDirs(sessionId), recycle))
965
- return { removed: gone.length, caches: cacheFiles.filter((file) => !fs.existsSync(file)).length }
966
- }
967
-
968
- // --- artifacts: what a session touched, and quarantining it -----------------
969
- //
970
- // "Produced files" is derived from the durable session log alone: the log is the
971
- // only record that outlives a closed Session (the host's own observation state
972
- // lives in a plugin-local WeakMap and dies with the process, and the
973
- // `workspace/changes` summaries live in a temporary directory that disposal
974
- // removes). Classification rests on one invariant of the default
975
- // fs-observation-policy: `write` may not overwrite a file that was not read
976
- // first, and `edit` requires a prior read. So a write whose path has no earlier
977
- // successful read CREATED the file; anything else already existed.
978
- //
979
- // Nothing here deletes. Files are moved into a timestamped quarantine directory
980
- // under $DSH_HOME, keeping their path relative to the session's working
981
- // directory, so a wrong call is recoverable.
982
-
983
- const QUARANTINE_PREFIX = 'purge-quarantine'
984
- const MAX_LISTED = 500
985
- /**
986
- * How many distinct paths one scan will resolve. Every path costs a realpath,
987
- * and a session that walked a large tree can name tens of thousands of them;
988
- * the dialog would sit on "scanning" for as long as they take. Past this the
989
- * plan reports `truncated`, which the dialog already surfaces.
990
- */
991
- const MAX_SCANNED = 2000
992
- /** How many path resolutions run at once: enough to hide the threadpool round trip, few enough to stay polite. */
993
- const RESOLVE_CONCURRENCY = 16
994
- /** How many directories the folder picker lists before saying there are more. */
995
- const MAX_BROWSE_ENTRIES = 500
996
- /** How long the OS chooser may stay open before the request gives up on it. */
997
- const PICK_TIMEOUT_MS = 5 * 60 * 1000
998
- /** How long a shell helper (the recycle-bin script) may run before giving up. */
999
- const SHELL_TIMEOUT_MS = 5 * 60 * 1000
1000
-
1001
- /** Run a program and collect its output, leaving the meaning of the exit to the caller. */
1002
- function runExecutable(program, args, timeoutMs) {
1003
- return new Promise((resolve, reject) => {
1004
- const child = spawn(program, args, { windowsHide: true })
1005
- let out = ''
1006
- let err = ''
1007
- let settled = false
1008
- const finish = (fn, value) => {
1009
- if (settled) return
1010
- settled = true
1011
- clearTimeout(timer)
1012
- fn(value)
1013
- }
1014
- const timer = setTimeout(() => {
1015
- try { child.kill() } catch { /* already gone */ }
1016
- finish(reject, new HttpError(504, 'timeout', '等待系统对话框超时'))
1017
- }, timeoutMs)
1018
-
1019
- child.stdout.on('data', (chunk) => { out += chunk.toString('utf8') })
1020
- child.stderr.on('data', (chunk) => { err += chunk.toString('utf8') })
1021
- child.on('error', (error) => {
1022
- finish(reject, new HttpError(500, 'spawn', `无法启动 ${path.basename(program)}:${String((error && error.message) || error)}`))
1023
- })
1024
- child.on('close', (code) => finish(resolve, { code, stdout: out, stderr: err }))
1025
- })
1026
- }
1027
-
1028
- /** Argument keys carrying the target path, per writing tool. */
1029
- const WRITE_TOOL_PATHS = {
1030
- write: ['file_path', 'path'],
1031
- edit: ['file_path', 'path'],
1032
- str_replace_editor: ['path', 'file_path'],
1033
- create_file: ['file_path', 'path'],
1034
- }
1035
-
1036
- /** Argument keys carrying the target path, per reading tool. */
1037
- const READ_TOOL_PATHS = {
1038
- read: ['file_path', 'path'],
1039
- read_file: ['file_path', 'path'],
1040
- }
1041
-
1042
- /**
1043
- * Resolve the target path one tool call names.
1044
- * @param name - tool name.
1045
- * @param argumentsJson - the model's raw argument JSON.
1046
- * @param cwd - the session's recorded working directory, for relative paths.
1047
- * @returns the absolute path and whether the tool writes, or undefined.
1048
- */
1049
- function toolTarget(name, argumentsJson, cwd) {
1050
- const writes = Object.prototype.hasOwnProperty.call(WRITE_TOOL_PATHS, name)
1051
- const keys = writes ? WRITE_TOOL_PATHS[name] : READ_TOOL_PATHS[name]
1052
- if (keys === undefined) return undefined
1053
- let args
1054
- try {
1055
- args = JSON.parse(typeof argumentsJson === 'string' ? argumentsJson : '')
1056
- } catch {
1057
- return undefined
1058
- }
1059
- if (args === null || typeof args !== 'object' || Array.isArray(args)) return undefined
1060
- const raw = keys.map((key) => args[key]).find((value) => typeof value === 'string' && value.trim() !== '')
1061
- if (raw === undefined) return undefined
1062
- let absolute
1063
- if (path.isAbsolute(raw)) absolute = raw
1064
- else if (cwd === undefined) return undefined
1065
- else absolute = path.resolve(cwd, raw)
1066
- return { path: absolute, writes }
1067
- }
1068
-
1069
- /** Read a stored session's events through the persistence seam. */
1070
- async function readSessionEvents(ctx, sessionId) {
1071
- const sp = ctx.get('sessionPersistence')
1072
- if (!sp || typeof sp.open !== 'function') {
1073
- return { events: [], warning: '持久化服务不可用,无法读取会话日志' }
1074
- }
1075
- let handle = null
1076
- try {
1077
- handle = await sp.open(sessionId, 'read')
1078
- const result = await handle.read()
1079
- const events = Array.isArray(result && result.events) ? result.events : []
1080
- return { events, warning: undefined }
1081
- } catch (error) {
1082
- return { events: [], warning: `读取会话日志失败:${String((error && error.message) || error)}` }
1083
- } finally {
1084
- try {
1085
- if (handle && typeof handle.close === 'function') await handle.close()
1086
- } catch {
1087
- // a close failure must not change the plan
1088
- }
1089
- }
1090
- }
1091
-
1092
- /**
1093
- * Identity of one path for "have we seen this file before?" purposes. The real
1094
- * path when it resolves, so a symlink alias and its target count as the same
1095
- * file; otherwise a case-folded resolved path on Windows, whose filesystem does
1096
- * not distinguish `Foo.md` from `foo.md`. Comparing spellings instead would let
1097
- * a write through an alias look like a creation.
1098
- * @param absolute - the path a tool call named.
1099
- * @param cache - optional per-scan memo; without it the resolution cost scales
1100
- * with log length rather than with the number of distinct files.
1101
- * @returns a stable key for the file, not for the spelling.
1102
- */
1103
- async function identityKey(absolute, cache) {
1104
- if (cache !== undefined) {
1105
- const hit = cache.get(absolute)
1106
- if (hit !== undefined) return hit
1107
- }
1108
- let key
1109
- try {
1110
- key = await realpathNative(absolute)
1111
- } catch {
1112
- const resolved = path.resolve(absolute)
1113
- key = process.platform === 'win32' ? resolved.toLowerCase() : resolved
1114
- }
1115
- if (cache !== undefined) cache.set(absolute, key)
1116
- return key
1117
- }
1118
-
1119
- /**
1120
- * Every path this session's writing tools touched, split by whether the session
1121
- * created it or found it already there.
1122
- * @param events - stored session events, in order.
1123
- * @param cwd - the session's recorded working directory.
1124
- * @param cache - optional per-scan memo for path resolution, shared across calls.
1125
- * @returns `{ created, modified }`, keyed by file identity, each row `{ path, identity, ops }`.
1126
- */
1127
- async function collectSessionPaths(events, cwd, cache) {
1128
- const pending = new Map()
1129
- const read = new Set()
1130
- const created = new Map()
1131
- const modified = new Map()
1132
- const memo = cache !== undefined ? cache : new Map()
1133
-
1134
- // Resolve every distinct path the log names first, together. A long session
1135
- // names the same handful of files thousands of times, so awaiting per call
1136
- // would buy one threadpool round trip per mention; this buys one per file.
1137
- const named = new Set()
1138
- let overflow = false
1139
- for (const event of events) {
1140
- const data = event && event.data
1141
- if (!data || typeof data !== 'object' || event.type !== 'tool/call') continue
1142
- const target = toolTarget(typeof data.name === 'string' ? data.name : '', data.arguments, cwd)
1143
- if (target === undefined) continue
1144
- if (named.size >= MAX_SCANNED && !named.has(target.path)) {
1145
- overflow = true
1146
- break
1147
- }
1148
- named.add(target.path)
1149
- }
1150
- await runWithConcurrency([...named], RESOLVE_CONCURRENCY, async (absolute) => {
1151
- await identityKey(absolute, memo)
1152
- })
1153
-
1154
- const commit = (call) => {
1155
- // A file the session created and later edited stays "created": one identity
1156
- // must never sit in both buckets, or a scope=all run would target it twice
1157
- // and report a spurious failure for the second attempt.
1158
- const alreadyCreated = created.get(call.identity)
1159
- if (alreadyCreated !== undefined) {
1160
- alreadyCreated.ops += 1
1161
- return
1162
- }
1163
- const bucket = call.existedBefore ? modified : created
1164
- const prior = bucket.get(call.identity)
1165
- if (prior !== undefined) prior.ops += 1
1166
- else bucket.set(call.identity, { path: call.path, identity: call.identity, ops: 1 })
1167
- }
1168
-
1169
- for (const event of events) {
1170
- const data = event && event.data
1171
- if (!data || typeof data !== 'object') continue
1172
-
1173
- if (event.type === 'tool/call') {
1174
- const name = typeof data.name === 'string' ? data.name : ''
1175
- const target = toolTarget(name, data.arguments, cwd)
1176
- // Existence is decided at call time, against the reads that already
1177
- // succeeded - the policy's own ordering - and on identity, so an alias of
1178
- // a file the session read is still an edit.
1179
- if (target !== undefined) {
1180
- const identity = await identityKey(target.path, memo)
1181
- pending.set(data.callId, {
1182
- path: target.path,
1183
- identity,
1184
- writes: target.writes,
1185
- existedBefore: read.has(identity),
1186
- })
1187
- }
1188
- continue
1189
- }
1190
-
1191
- if (event.type !== 'tool/result') continue
1192
- const message = data.message
1193
- const callId = message && typeof message.toolCallId === 'string' ? message.toolCallId : undefined
1194
- if (callId === undefined) continue
1195
- const call = pending.get(callId)
1196
- if (call === undefined) continue
1197
- pending.delete(callId)
1198
- if (data.error !== undefined || (message && message.isError === true)) continue
1199
- if (call.writes) commit(call)
1200
- else read.add(call.identity)
1201
- }
1202
-
1203
- return { named: named.size, overflow, created, modified }
1204
- }
1205
-
1206
- /**
1207
- * Whether `child` is strictly inside `parent`, comparing real paths. Folded on
1208
- * Windows, where the filesystem ignores case: a realpath does not normalise the
1209
- * case of a prefix that still matches a differently-spelled spelling.
1210
- */
1211
- function insidePath(parent, child) {
1212
- if (parent === child) return false
1213
- const fold = (value) => (process.platform === 'win32' ? value.toLowerCase() : value)
1214
- const base = fold(parent)
1215
- const prefix = base.endsWith(path.sep) ? base : base + path.sep
1216
- return fold(child).startsWith(prefix)
1217
- }
1218
-
1219
- /**
1220
- * Is this directory inside a git working tree? A `.git` entry marks the root —
1221
- * a directory in a normal clone, a file in a worktree or a submodule.
1222
- *
1223
- * The walk memoises per directory: one plan can span hundreds of files that share
1224
- * a handful of folders, and each miss would otherwise stat every level again.
1225
- */
1226
- async function isInsideGitRepo(directory, cache) {
1227
- let current = path.resolve(directory)
1228
- const walked = []
1229
- for (;;) {
1230
- if (cache.has(current)) {
1231
- const verdict = cache.get(current)
1232
- for (const dir of walked) cache.set(dir, verdict)
1233
- return verdict
1234
- }
1235
- walked.push(current)
1236
- try {
1237
- const marker = await fsp.stat(path.join(current, '.git'))
1238
- if (marker.isDirectory() || marker.isFile()) {
1239
- for (const dir of walked) cache.set(dir, true)
1240
- return true
1241
- }
1242
- } catch {
1243
- // no .git here; keep walking up
1244
- }
1245
- const parent = path.dirname(current)
1246
- if (parent === current) {
1247
- for (const dir of walked) cache.set(dir, false)
1248
- return false
1249
- }
1250
- current = parent
1251
- }
1252
- }
1253
-
1254
- /**
1255
- * Keep only the paths that may actually be moved: an existing regular file whose
1256
- * real path is strictly inside the session's working directory and outside the
1257
- * DSH home. Every rejection carries its reason.
1258
- * @param rows - candidate rows `{ path, ops }`.
1259
- * @param cwd - the session's recorded working directory.
1260
- * @param home - resolved DSH home.
1261
- * @param options - `{ skipGit }`: also refuse files inside a git working tree.
1262
- * @returns `{ allowed, refused }`.
1263
- */
1264
- async function classifyPaths(rows, cwd, home, options) {
1265
- const allowed = []
1266
- const refused = []
1267
- const skipGit = options !== undefined && options !== null && options.skipGit === true
1268
- const gitCache = new Map()
1269
- const list = [...rows.values()]
1270
- if (cwd === undefined) {
1271
- for (const row of list) refused.push({ path: row.path, reason: '会话未记录工作目录,无法安全定位' })
1272
- return { allowed, refused }
1273
- }
1274
- let realCwd
1275
- try {
1276
- realCwd = await fsp.realpath(cwd)
1277
- } catch {
1278
- for (const row of list) refused.push({ path: row.path, reason: '会话工作目录已不存在,无法校验归属' })
1279
- return { allowed, refused }
1280
- }
1281
- let realHome = home
1282
- try {
1283
- realHome = await fsp.realpath(home)
1284
- } catch {
1285
- // an absent home cannot contain anything that exists
1286
- }
1287
- // Resolve each row's stat and real path together rather than one after another:
1288
- // a long session can list hundreds of files, and awaiting them serially turns
1289
- // one threadpool round trip into hundreds. `runWithConcurrency` keeps the order.
1290
- const verdicts = await runWithConcurrency(list, RESOLVE_CONCURRENCY, async (row) => {
1291
- let info
1292
- try {
1293
- info = await fsp.stat(row.path)
1294
- } catch {
1295
- return { refuse: { path: row.path, reason: '文件已不存在' } }
1296
- }
1297
- if (!info.isFile()) return { refuse: { path: row.path, reason: '不是普通文件,已跳过' } }
1298
- let real
1299
- try {
1300
- real = await fsp.realpath(row.path)
1301
- } catch {
1302
- return { refuse: { path: row.path, reason: '无法解析真实路径,已跳过' } }
1303
- }
1304
- if (!insidePath(realCwd, real)) {
1305
- return { refuse: { path: row.path, reason: '不在该对话的工作目录内,已跳过' } }
1306
- }
1307
- if (insidePath(realHome, real)) {
1308
- return { refuse: { path: row.path, reason: '位于 DSH 数据目录内,已跳过' } }
1309
- }
1310
- if (skipGit && await isInsideGitRepo(path.dirname(real), gitCache)) {
1311
- return { refuse: { path: row.path, reason: '位于 git 仓库内,已跳过' } }
1312
- }
1313
- return { allow: { path: real, displayPath: row.path, ops: row.ops, bytes: info.size, mtime: info.mtimeMs } }
1314
- })
1315
- for (const verdict of verdicts) {
1316
- if (verdict.allow !== undefined) allowed.push(verdict.allow)
1317
- else refused.push(verdict.refuse)
1318
- }
1319
- return { allowed, refused }
1320
- }
1321
-
1322
- /**
1323
- * Build the artifact plan for one session.
1324
- * @param ctx - host plugin context.
1325
- * @param sessionId - validated session id.
1326
- * @returns `{ cwd, created, modified, refused, truncated, warnings }`.
1327
- */
1328
- async function planArtifacts(ctx, sessionId, cache, options) {
1329
- const home = dshHome()
1330
- const warnings = []
1331
- const sp = ctx.get('sessionPersistence')
1332
- let cwd
1333
- if (sp && typeof sp.stat === 'function') {
1334
- try {
1335
- const snapshot = await sp.stat(sessionId)
1336
- let header = null
1337
- if (snapshot !== null && typeof snapshot === 'object') {
1338
- header = snapshot.header !== null && typeof snapshot.header === 'object' ? snapshot.header : snapshot
1339
- }
1340
- if (header && typeof header.cwd === 'string' && header.cwd !== '') cwd = header.cwd
1341
- } catch (error) {
1342
- warnings.push(`未找到该会话的存储记录:${String((error && error.message) || error)}`)
1343
- }
1344
- }
1345
- const { events, warning } = await readSessionEvents(ctx, sessionId)
1346
- if (warning !== undefined) warnings.push(warning)
1347
- const scan = await collectSessionPaths(events, cwd, cache)
1348
- const { created, modified } = scan
1349
- const createdPlan = await classifyPaths(created, cwd, home, options)
1350
- const modifiedPlan = await classifyPaths(modified, cwd, home, options)
1351
- const refused = [...createdPlan.refused, ...modifiedPlan.refused]
1352
- return {
1353
- // Stamped so a caller handing this plan back cannot smuggle in another
1354
- // session's list: runQuarantine refuses a plan that does not belong here.
1355
- sessionId,
1356
- cwd,
1357
- created: createdPlan.allowed.slice(0, MAX_LISTED),
1358
- modified: modifiedPlan.allowed.slice(0, MAX_LISTED),
1359
- refused: refused.slice(0, MAX_LISTED),
1360
- truncated: scan.overflow
1361
- || createdPlan.allowed.length > MAX_LISTED
1362
- || modifiedPlan.allowed.length > MAX_LISTED
1363
- || refused.length > MAX_LISTED,
1364
- warnings,
1365
- }
1366
- }
1367
-
1368
- /**
1369
- * Claim a quarantine directory under the DSH home. The name carries second
1370
- * resolution only, so two deletes can land on the same name; an exclusive mkdir
1371
- * (never `recursive: true`, which would happily reuse an existing tree) decides
1372
- * the winner and the loser retries with a suffix. Two runs therefore can never
1373
- * share a tree, which is what stops one run's file from overwriting another's.
1374
- * @param home - resolved DSH home.
1375
- * @returns the claimed directory, or undefined when none could be claimed.
1376
- */
1377
- async function claimQuarantineDirectory(home) {
1378
- // A fresh home has no quarantine root yet; creating it is the only write this
1379
- // side does outside the quarantine tree, and it keeps a missing home from
1380
- // turning into a silent "cannot claim" on the very first delete.
1381
- try {
1382
- await fsp.mkdir(home, { recursive: true })
1383
- } catch {
1384
- return undefined
1385
- }
1386
- const base = `${QUARANTINE_PREFIX}-${new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)}`
1387
- for (let attempt = 0; attempt < 1000; attempt += 1) {
1388
- const candidate = path.join(home, attempt === 0 ? base : `${base}-${attempt}`)
1389
- try {
1390
- await fsp.mkdir(candidate, { recursive: false })
1391
- return candidate
1392
- } catch (error) {
1393
- if (error && error.code === 'EEXIST') continue
1394
- return undefined
1395
- }
1396
- }
1397
- return undefined
1398
- }
1399
-
1400
- /** Whether a path exists, without throwing. */
1401
- async function pathExists(target) {
1402
- try {
1403
- await fsp.access(target)
1404
- return true
1405
- } catch {
1406
- return false
1407
- }
1408
- }
1409
-
1410
- /**
1411
- * A destination inside the quarantine tree that does not already exist. The
1412
- * move itself must never overwrite: a quarantine that silently replaced an
1413
- * earlier copy would destroy the only surviving copy of the file it replaced.
1414
- * @param directory - claimed quarantine directory.
1415
- * @param relative - path relative to the session's working directory.
1416
- * @returns a free absolute path, or undefined when every name was taken.
1417
- */
1418
- async function freeDestination(directory, relative) {
1419
- const first = path.join(directory, relative)
1420
- if (!(await pathExists(first))) return first
1421
- const dir = path.dirname(first)
1422
- const ext = path.extname(first)
1423
- const stem = path.basename(first, ext)
1424
- for (let n = 1; n < 10000; n += 1) {
1425
- const candidate = path.join(dir, `${stem}-${n}${ext}`)
1426
- if (!(await pathExists(candidate))) return candidate
1427
- }
1428
- return undefined
1429
- }
1430
-
1431
- /**
1432
- * Move the chosen files into a timestamped quarantine directory under the DSH
1433
- * home, preserving each path relative to the session's working directory. Files
1434
- * are moved, never removed, and an existing quarantine entry is never replaced,
1435
- * so a wrong call is always recoverable by hand.
1436
- *
1437
- * Every step is asynchronous on purpose: a cross-device move copies, and a
1438
- * synchronous copy inside the request handler would freeze the event loop, which
1439
- * means every other session's traffic stalls behind one large quarantine.
1440
- *
1441
- * @param targets - absolute file paths to move.
1442
- * @param cwd - the session's recorded working directory.
1443
- * @param home - resolved DSH home.
1444
- * @returns `{ directory, moved, failed }`.
1445
- */
1446
- async function quarantineFiles(targets, cwd, home) {
1447
- const moved = []
1448
- const failed = []
1449
- if (targets.length === 0) return { directory: null, moved, failed }
1450
-
1451
- const directory = await claimQuarantineDirectory(home)
1452
- if (directory === undefined) {
1453
- for (const target of targets) failed.push({ path: target, error: '无法创建隔离目录' })
1454
- return { directory: null, moved, failed }
1455
- }
1456
-
1457
- let realCwd = cwd
1458
- if (typeof cwd === 'string') {
1459
- try {
1460
- realCwd = await fsp.realpath(cwd)
1461
- } catch {
1462
- // keep the recorded spelling; classifyPaths already proved containment
1463
- }
1464
- }
1465
- for (const target of targets) {
1466
- let relative = path.basename(target)
1467
- if (typeof realCwd === 'string') {
1468
- const candidate = path.relative(realCwd, target)
1469
- if (candidate !== '' && !candidate.startsWith('..') && !path.isAbsolute(candidate)) relative = candidate
1470
- }
1471
- try {
1472
- await fsp.mkdir(path.dirname(path.join(directory, relative)), { recursive: true })
1473
- const destination = await freeDestination(directory, relative)
1474
- if (destination === undefined) {
1475
- failed.push({ path: target, error: '隔离目录内没有可用的目标文件名' })
1476
- continue
1477
- }
1478
- try {
1479
- await fsp.rename(target, destination)
1480
- } catch {
1481
- // A cross-device rename fails; fall back to copy-then-remove. `COPYFILE_EXCL`
1482
- // keeps the copy from replacing anything that appeared in between.
1483
- await fsp.copyFile(target, destination, fs.constants.COPYFILE_EXCL)
1484
- await fsp.rm(target, { force: true })
1485
- }
1486
- moved.push({ from: target, to: destination })
1487
- } catch (error) {
1488
- failed.push({ path: target, error: String((error && error.message) || error) })
1489
- }
1490
- }
1491
- return { directory, moved, failed }
1492
- }
1493
-
1494
- /**
1495
- * The files one plan actually offered. The per-file delete button sends back a
1496
- * path from this list, and the route refuses anything else: a request cannot
1497
- * name a file the user was never shown.
1498
- *
1499
- * @param plan - the artifact plan this plugin produced for a session.
1500
- * @returns every listed path, created and modified alike.
1501
- */
1502
- function artifactCandidates(plan) {
1503
- const out = []
1504
- for (const group of [plan.created, plan.modified]) {
1505
- if (!Array.isArray(group)) continue
1506
- for (const row of group) {
1507
- if (row !== null && row !== undefined && typeof row.path === 'string') out.push(row.path)
1508
- }
1509
- }
1510
- return out
1511
- }
1512
-
1513
- /**
1514
- * The path a per-file delete may touch: one the plan listed, nothing else.
1515
- * Without this the button would be a general-purpose delete primitive reachable
1516
- * from the page.
1517
- *
1518
- * @param plan - the artifact plan for the session.
1519
- * @param target - the path the page asked for.
1520
- * @returns the resolved path, ready to unlink.
1521
- */
1522
- function assertListedPath(plan, target) {
1523
- const resolved = path.resolve(target)
1524
- const listed = artifactCandidates(plan).some((candidate) => path.resolve(candidate) === resolved)
1525
- if (!listed) throw new HttpError(403, 'not-listed', '该文件不在本对话的产出清单里')
1526
- return resolved
1527
- }
1528
-
1529
- /**
1530
- * Delete one produced file. The destination is the user's call, and the dialog
1531
- * passes the same preference that governs a conversation delete: to the system
1532
- * trash, or outright.
1533
- *
1534
- * @param target - absolute path of the file.
1535
- * @param recycle - true to send it to the system recycle bin.
1536
- * @returns `{ recycled }` describing where it went.
1537
- */
1538
- async function removeOneFile(target, recycle) {
1539
- const resolved = path.resolve(target)
1540
- let info
1541
- try {
1542
- info = await fsp.lstat(resolved)
1543
- } catch (error) {
1544
- throw new HttpError(404, 'missing', `文件已不存在:${String((error && error.message) || error)}`)
1545
- }
1546
- if (!info.isFile()) throw new HttpError(400, 'not-a-file', '只能删除普通文件')
1547
- if (recycle === true) {
1548
- const ok = await sendToRecycleBin([resolved])
1549
- if (!ok) throw new HttpError(500, 'recycle', '移入回收站失败')
1550
- return { recycled: true }
1551
- }
1552
- try {
1553
- await fsp.unlink(resolved)
1554
- } catch (error) {
1555
- throw new HttpError(500, 'unlink', `删除失败:${String((error && error.message) || error)}`)
1556
- }
1557
- return { recycled: false }
1558
- }
1559
-
1560
- /**
1561
- * Quarantine the files one request selected. The candidate set is recomputed
1562
- * here from the session log and the request's paths are intersected with it, so
1563
- * a tampered request cannot move anything the user was not shown.
1564
- * @param ctx - host plugin context.
1565
- * @param sessionId - validated session id.
1566
- * @param request - `{ scope, paths }` from the client; undefined asks for none.
1567
- * @returns the outcome, or null when the request asked for no quarantine.
1568
- */
1569
- async function runQuarantine(ctx, sessionId, request, knownPlan) {
1570
- if (request === undefined || request === null || typeof request !== 'object') return null
1571
- // Validated here as well as at the route, because `internals` exposes this
1572
- // function and a direct caller must not be able to skip the check.
1573
- if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
1574
- const scope = request.scope === 'all' ? 'all' : 'created'
1575
- // The same flag the dialog was built with, so a derived set cannot contain a
1576
- // file the listing refused to show.
1577
- const skipGit = request.skipGit === true
1578
- // Re-deriving the plan is the expensive half of a delete; a caller that already
1579
- // holds it for this session hands it over instead of paying for it twice.
1580
- const plan = knownPlan === undefined || knownPlan === null
1581
- ? await planArtifacts(ctx, sessionId, undefined, { skipGit })
1582
- : knownPlan
1583
- // A handed-in plan must be this session's plan. The route always derives it
1584
- // from the same id, but `internals` exposes this function, and a future caller
1585
- // passing its neighbour's plan would move files the user never saw.
1586
- if (plan.sessionId !== sessionId) throw new HttpError(400, 'invalid', 'plan does not belong to this session')
1587
- const candidates = scope === 'all' ? [...plan.created, ...plan.modified] : [...plan.created]
1588
- const allowed = new Set(candidates.map((row) => row.path))
1589
- const requested = Array.isArray(request.paths) ? request.paths : null
1590
- const requestedStrings = requested === null ? null : new Set(requested.filter((value) => typeof value === 'string'))
1591
- const targets = requested === null
1592
- ? [...allowed]
1593
- : [...requestedStrings].filter((value) => allowed.has(value))
1594
- // Resolve the configured save path before moving a single file: a bad path must
1595
- // stop the request, not send the files somewhere unintended.
1596
- const rootInfo = await resolveQuarantineRoot(request.root, plan.cwd)
1597
- if (rootInfo.error !== undefined) throw new HttpError(400, 'invalid', rootInfo.error)
1598
- const root = rootInfo.root
1599
- const outcome = await quarantineFiles(targets, plan.cwd, root)
1600
- return {
1601
- scope,
1602
- directory: outcome.moved.length > 0 ? outcome.directory : null,
1603
- root,
1604
- moved: outcome.moved,
1605
- failed: outcome.failed,
1606
- candidates: allowed.size,
1607
- selected: targets.length,
1608
- dropped: requestedStrings === null ? 0 : requestedStrings.size - targets.length,
1609
- }
1610
- }
1611
-
1612
- /**
1613
- * Decide which directory the timestamped quarantine folder is created under. An
1614
- * empty request means the DSH home, which is what every earlier version did.
1615
- * @param requested - the directory the client asked for, if any.
1616
- * @param cwd - the session's working directory, used to refuse a "quarantine"
1617
- * that would only shuffle the files around inside the tree they came from.
1618
- * @returns `{ root }` or `{ error }`.
1619
- */
1620
- async function resolveQuarantineRoot(requested, cwd) {
1621
- const home = dshHome()
1622
- if (requested === undefined || requested === null || requested === '') return { root: home }
1623
- if (typeof requested !== 'string') return { error: '保存路径必须是字符串' }
1624
- if (requested.length > 4096) return { error: '保存路径过长' }
1625
- if (!path.isAbsolute(requested)) return { error: '保存路径必须是绝对路径' }
1626
-
1627
- let real
1628
- try {
1629
- real = await fsp.realpath(requested)
1630
- } catch {
1631
- return { error: `保存路径不存在:${requested}` }
1632
- }
1633
- let info
1634
- try {
1635
- info = await fsp.stat(real)
1636
- } catch {
1637
- return { error: `无法读取保存路径:${requested}` }
1638
- }
1639
- if (!info.isDirectory()) return { error: '保存路径不是目录' }
1640
-
1641
- // The sessions store belongs to DSH; filling it with quarantined files would
1642
- // drop them back into the one tree the delete pipeline sweeps.
1643
- const sessionsRoot = path.join(home, 'sessions')
1644
- if (real === sessionsRoot || insidePath(sessionsRoot, real)) {
1645
- return { error: '不能把隔离夹设在会话存储目录内' }
1646
- }
1647
- if (typeof cwd === 'string') {
1648
- let realCwd
1649
- try {
1650
- realCwd = await fsp.realpath(cwd)
1651
- } catch {
1652
- realCwd = undefined
1653
- }
1654
- if (realCwd !== undefined && (real === realCwd || insidePath(realCwd, real))) {
1655
- return { error: '不能把隔离夹设在会话工作目录内' }
1656
- }
1657
- }
1658
- return { root: real }
1659
- }
1660
-
1661
- /** The drive letters Windows exposes, skipping the ones that cannot be read. */
1662
- async function listDriveRoots() {
1663
- if (process.platform !== 'win32') return []
1664
- const roots = []
1665
- for (let code = 65; code <= 90; code += 1) {
1666
- const drive = `${String.fromCharCode(code)}:\\`
1667
- try {
1668
- await fsp.access(drive)
1669
- roots.push({ name: drive, path: drive })
1670
- } catch {
1671
- // absent or unreadable: not offered
1672
- }
1673
- }
1674
- return roots
1675
- }
1676
-
1677
- /**
1678
- * One directory listing for the folder picker. Directories only: the picker
1679
- * chooses where a folder is created, so files would be noise.
1680
- * @param target - absolute directory to list; the DSH home when omitted.
1681
- */
1682
- async function listDirectories(target) {
1683
- const home = dshHome()
1684
- const start = target === undefined || target === null || target === '' ? home : target
1685
- if (typeof start !== 'string') throw new HttpError(400, 'invalid', 'path must be a string')
1686
- if (!path.isAbsolute(start)) throw new HttpError(400, 'invalid', 'path must be absolute')
1687
-
1688
- let real
1689
- try {
1690
- real = await fsp.realpath(start)
1691
- } catch {
1692
- throw new HttpError(400, 'invalid', `目录不存在:${start}`)
1693
- }
1694
- let entries
1695
- try {
1696
- entries = await fsp.readdir(real, { withFileTypes: true })
1697
- } catch (error) {
1698
- throw new HttpError(400, 'invalid', `无法读取目录:${String((error && error.message) || error)}`)
1699
- }
1700
-
1701
- const directories = []
1702
- for (const entry of entries) {
1703
- if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
1704
- const full = path.join(real, entry.name)
1705
- try {
1706
- // `stat` follows a link, so a shortcut to a folder is still offered.
1707
- const info = await fsp.stat(full)
1708
- if (!info.isDirectory()) continue
1709
- } catch {
1710
- continue
1711
- }
1712
- directories.push({ name: entry.name, path: full })
1713
- }
1714
- directories.sort((a, b) => a.name.localeCompare(b.name))
1715
-
1716
- const parent = real === path.parse(real).root ? null : path.dirname(real)
1717
- return {
1718
- path: real,
1719
- parent,
1720
- entries: directories.slice(0, MAX_BROWSE_ENTRIES),
1721
- truncated: directories.length > MAX_BROWSE_ENTRIES,
1722
- // At a drive root, offer the other drives so Windows users are not stranded.
1723
- roots: parent === null ? await listDriveRoots() : [],
1724
- defaultRoot: home,
1725
- }
1726
- }
1727
-
1728
- /**
1729
- * Run one PowerShell invocation and resolve its trimmed stdout.
1730
- *
1731
- * The script is passed as a file, never on stdin: `-Command -` reads stdin with
1732
- * the console code page, and a non-ASCII byte in the script (the Chinese dialog
1733
- * description, for one) silently killed the whole run instead of erroring.
1734
- */
1735
- function runPowershell(args, timeoutMs) {
1736
- return new Promise((resolve, reject) => {
1737
- const child = spawn('powershell.exe', args, {
1738
- windowsHide: true,
1739
- })
1740
- let out = ''
1741
- let err = ''
1742
- let settled = false
1743
- const finish = (fn, value) => {
1744
- if (settled) return
1745
- settled = true
1746
- clearTimeout(timer)
1747
- fn(value)
1748
- }
1749
- const timer = setTimeout(() => {
1750
- try { child.kill() } catch { /* already gone */ }
1751
- finish(reject, new HttpError(504, 'timeout', '等待系统对话框超时'))
1752
- }, timeoutMs)
1753
-
1754
- child.stdout.on('data', (chunk) => { out += chunk.toString('utf8') })
1755
- child.stderr.on('data', (chunk) => { err += chunk.toString('utf8') })
1756
- child.on('error', (error) => {
1757
- finish(reject, new HttpError(500, 'spawn', `无法启动系统对话框:${String((error && error.message) || error)}`))
1758
- })
1759
- child.on('close', (code) => {
1760
- if (code !== 0) {
1761
- finish(reject, new HttpError(500, 'shell', `系统对话框异常退出(${code}):${err.trim().slice(0, 300)}`))
1762
- return
1763
- }
1764
- finish(resolve, out.trim())
1765
- })
1766
- })
1767
- }
1768
-
1769
- /**
1770
- * Open a directory in the operating system's file manager. The child is detached
1771
- * and unreferenced so the HTTP response returns at once and the window lives on
1772
- * its own; `explorer.exe` reports a non-zero exit even when it succeeds, so its
1773
- * status is deliberately ignored.
1774
- */
1775
- function revealDirectory(directory) {
1776
- const opener = process.platform === 'win32'
1777
- ? { program: 'explorer.exe', args: [directory] }
1778
- : process.platform === 'darwin'
1779
- ? { program: 'open', args: [directory] }
1780
- : { program: 'xdg-open', args: [directory] }
1781
- const child = spawn(opener.program, opener.args, { detached: true, stdio: 'ignore', windowsHide: false })
1782
- // Without this listener a failed spawn (explorer missing, blocked by security
1783
- // software) surfaces as an unhandled `error` event and takes the host down.
1784
- child.on('error', () => {})
1785
- child.unref()
1786
- }
1787
-
1788
- /**
1789
- * Ask the host for a directory.
1790
- *
1791
- * DSH mounts `ctx.directoryPicker` (`@deepseek-ai/dsh-host-directory-picker-auto`),
1792
- * whose capability names the interaction this deployment supports: a native
1793
- * deployment opens one OS chooser, a browse deployment serves a listing the page
1794
- * draws itself. Consumers are meant to switch on `capability().kind`.
1795
- *
1796
- * This plugin used to compile its own C# chooser and fall back to PowerShell. That
1797
- * was a reimplementation of something the host already ships, it could not follow a
1798
- * remote deployment, and it needed a compiler on the machine at first use.
1799
- *
1800
- * @returns `{ cancelled, path }` from a native chooser, else `{ browse: true }` or
1801
- * `{ unsupported: true }` so the page falls back to its own picker.
1802
- */
1803
- async function pickFolder(ctx) {
1804
- const picker = ctx !== null && ctx !== undefined && typeof ctx.get === 'function'
1805
- ? ctx.get('directoryPicker')
1806
- : undefined
1807
- if (picker === null || picker === undefined || typeof picker.capability !== 'function') {
1808
- return { unsupported: true }
1809
- }
1810
- let capability
1811
- try {
1812
- capability = picker.capability()
1813
- } catch {
1814
- return { unsupported: true }
1815
- }
1816
- if (capability === null || capability === undefined) return { unsupported: true }
1817
- if (capability.kind !== 'native' || typeof capability.pick !== 'function') return { browse: true }
1818
- // `pick(signal)` is mandatory: the host implementation begins with
1819
- // `if (signal.aborted) throw …`, so calling it bare throws a TypeError that
1820
- // reads like an unrelated failure ("… reading 'aborted'"). The timeout matches
1821
- // the one the previous PowerShell dialog used: a dialog nobody answers must not
1822
- // hold the request forever.
1823
- const controller = new AbortController()
1824
- const timer = setTimeout(() => controller.abort(), PICK_TIMEOUT_MS)
1825
- let picked
1826
- try {
1827
- picked = await capability.pick(controller.signal)
1828
- } finally {
1829
- clearTimeout(timer)
1830
- }
1831
- const chosen = typeof picked === 'string' && picked !== '' ? picked : null
1832
- if (chosen === null) return { cancelled: true, path: null }
1833
- const resolved = path.resolve(chosen)
1834
- let info
1835
- try {
1836
- info = await fsp.stat(resolved)
1837
- } catch {
1838
- throw new HttpError(400, 'invalid', '选中的目录已不存在')
1839
- }
1840
- if (!info.isDirectory()) throw new HttpError(400, 'invalid', '选中的不是目录')
1841
- return { cancelled: false, path: resolved }
1842
- }
1843
-
1844
-
1845
- // --- http --------------------------------------------------------------------
1846
-
1847
- function isLoopbackAddress(address) {
1848
- if (typeof address !== 'string' || address.length === 0) return false
1849
- return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1' || address.startsWith('127.')
1850
- }
1851
-
1852
- function isLocalHostHeader(host) {
1853
- if (typeof host !== 'string' || host.length === 0) return false
1854
- const name = host.split(':')[0].replace(/^\[|\]$/g, '').toLowerCase()
1855
- return name === 'localhost' || name === '127.0.0.1' || name === '::1'
1856
- }
1857
-
1858
- function sendJson(res, status, body) {
1859
- const payload = JSON.stringify(body)
1860
- res.writeHead(status, {
1861
- 'content-type': 'application/json; charset=utf-8',
1862
- 'content-length': Buffer.byteLength(payload),
1863
- })
1864
- res.end(payload)
1865
- }
1866
-
1867
- function readBody(req) {
1868
- return new Promise((resolve, reject) => {
1869
- let data = ''
1870
- req.on('data', (chunk) => {
1871
- data += chunk
1872
- if (data.length > 1e6) req.destroy()
1873
- })
1874
- req.on('end', () => resolve(data))
1875
- req.on('error', reject)
1876
- req.on('aborted', () => reject(new Error('aborted')))
1877
- })
1878
- }
1879
-
1880
- // Destructive local endpoint: loopback socket, loopback Host header, and a
1881
- // same-origin check when the browser sends Origin. Tunneled or LAN clients
1882
- // get 403 before any session data is touched.
1883
- function guard(req, res) {
1884
- if (!isLoopbackAddress(req.socket && req.socket.remoteAddress)) {
1885
- sendJson(res, 403, { ok: false, code: 'forbidden', error: 'loopback only' })
1886
- return false
1887
- }
1888
- const host = req.headers.host
1889
- if (!isLocalHostHeader(host)) {
1890
- sendJson(res, 403, { ok: false, code: 'forbidden', error: 'unexpected host' })
1891
- return false
1892
- }
1893
- const origin = req.headers.origin
1894
- if (typeof origin === 'string' && origin.length > 0) {
1895
- let originHost = null
1896
- try {
1897
- originHost = new URL(origin).host
1898
- } catch {
1899
- originHost = null
1900
- }
1901
- if (originHost !== host) {
1902
- sendJson(res, 403, { ok: false, code: 'forbidden', error: 'cross-origin request' })
1903
- return false
1904
- }
1905
- }
1906
- return true
1907
- }
1908
-
1909
- // --- plugin ------------------------------------------------------------------
1910
-
1911
- export function apply(ctx) {
1912
- warmCompiledHelpers()
1913
-
1914
- const registerRoutes = (webServer, fiber) => {
1915
- // Read-only scan: the dialog shows what a delete would move, before it does.
1916
- fiber.effect(() => webServer.register({
1917
- kind: 'exact',
1918
- path: `${ROUTE_PREFIX}/artifacts`,
1919
- handler: async (req, res) => {
1920
- if (!guard(req, res)) return
1921
- if (req.method !== 'POST') {
1922
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1923
- return
1924
- }
1925
- let body = {}
1926
- try {
1927
- const raw = await readBody(req)
1928
- if (raw) body = JSON.parse(raw)
1929
- } catch {
1930
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
1931
- return
1932
- }
1933
- const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
1934
- if (!sessionId) {
1935
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'sessionId required' })
1936
- return
1937
- }
1938
- try {
1939
- if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
1940
- const plan = await planArtifacts(ctx, sessionId, undefined, { skipGit: body.skipGit === true })
1941
- // A bad save path is reported alongside the plan rather than replacing
1942
- // it: the dialog can still show the files while saying where they cannot go.
1943
- const rootInfo = await resolveQuarantineRoot(body.root, plan.cwd)
1944
- sendJson(res, 200, {
1945
- ok: true,
1946
- sessionId,
1947
- ...plan,
1948
- defaultRoot: dshHome(),
1949
- quarantineRoot: rootInfo.error === undefined ? rootInfo.root : null,
1950
- rootError: rootInfo.error === undefined ? null : rootInfo.error,
1951
- })
1952
- } catch (error) {
1953
- const status = error instanceof HttpError ? error.status : 500
1954
- const code = error instanceof HttpError ? error.code : 'internal'
1955
- sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1956
- }
1957
- },
1958
- }))
1959
-
1960
- // Delete ONE produced file from the dialog. The path must be one the scan
1961
- // listed, so this cannot become a general-purpose delete primitive.
1962
- fiber.effect(() => webServer.register({
1963
- kind: 'exact',
1964
- path: `${ROUTE_PREFIX}/delete-file`,
1965
- handler: async (req, res) => {
1966
- if (!guard(req, res)) return
1967
- if (req.method !== 'POST') {
1968
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1969
- return
1970
- }
1971
- let body = {}
1972
- try {
1973
- const raw = await readBody(req)
1974
- if (raw) body = JSON.parse(raw)
1975
- } catch {
1976
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
1977
- return
1978
- }
1979
- const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
1980
- const target = typeof body.path === 'string' ? body.path.trim() : ''
1981
- try {
1982
- if (sessionId === '') throw new HttpError(400, 'invalid', 'sessionId required')
1983
- if (target === '') throw new HttpError(400, 'invalid', 'path required')
1984
- if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
1985
- const plan = await planArtifacts(ctx, sessionId, undefined, {})
1986
- const resolved = assertListedPath(plan, target)
1987
- const result = await removeOneFile(resolved, body.recycle === true)
1988
- sendJson(res, 200, { ok: true, ...result })
1989
- } catch (error) {
1990
- const status = error instanceof HttpError ? error.status : 500
1991
- const code = error instanceof HttpError ? error.code : 'internal'
1992
- sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1993
- }
1994
- },
1995
- }))
1996
-
1997
- // The real Windows folder dialog, raised on the user's behalf. Browsers cannot
1998
- // hand a page a filesystem path, but this process is local, so it can.
1999
- fiber.effect(() => webServer.register({
2000
- kind: 'exact',
2001
- path: `${ROUTE_PREFIX}/pick`,
2002
- handler: async (req, res) => {
2003
- if (!guard(req, res)) return
2004
- if (req.method !== 'POST') {
2005
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2006
- return
2007
- }
2008
- try {
2009
- const picked = await pickFolder(ctx)
2010
- if (picked.unsupported === true) {
2011
- sendJson(res, 200, { ok: false, code: 'unsupported', error: '宿主没有 directoryPicker 服务' })
2012
- return
2013
- }
2014
- if (picked.browse === true) {
2015
- sendJson(res, 200, { ok: false, code: 'browse', error: '浏览式宿主,请用页面内的选择器' })
2016
- return
2017
- }
2018
- sendJson(res, 200, { ok: true, ...picked })
2019
- } catch (error) {
2020
- const status = error instanceof HttpError ? error.status : 500
2021
- const code = error instanceof HttpError ? error.code : 'internal'
2022
- sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2023
- }
2024
- },
2025
- }))
2026
-
2027
- // Open a folder in the OS file manager. The path is validated as an existing
2028
- // directory first: this hands a string to Explorer, so it must never be able
2029
- // to carry anything but a directory.
2030
- fiber.effect(() => webServer.register({
2031
- kind: 'exact',
2032
- path: `${ROUTE_PREFIX}/reveal`,
2033
- handler: async (req, res) => {
2034
- if (!guard(req, res)) return
2035
- if (req.method !== 'POST') {
2036
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2037
- return
2038
- }
2039
- let body = {}
2040
- try {
2041
- const raw = await readBody(req)
2042
- if (raw) body = JSON.parse(raw)
2043
- } catch {
2044
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2045
- return
2046
- }
2047
- try {
2048
- const target = typeof body.path === 'string' ? body.path.trim() : ''
2049
- if (target === '') throw new HttpError(400, 'invalid', 'path required')
2050
- const resolved = path.resolve(target)
2051
- let info
2052
- try {
2053
- info = await fsp.stat(resolved)
2054
- } catch {
2055
- throw new HttpError(400, 'invalid', '目录不存在')
2056
- }
2057
- if (!info.isDirectory()) throw new HttpError(400, 'invalid', '不是目录')
2058
- revealDirectory(resolved)
2059
- sendJson(res, 200, { ok: true, path: resolved })
2060
- } catch (error) {
2061
- const status = error instanceof HttpError ? error.status : 500
2062
- const code = error instanceof HttpError ? error.code : 'internal'
2063
- sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2064
- }
2065
- },
2066
- }))
2067
-
2068
- // Folder picker for the quarantine save path: directories only, never file
2069
- // contents, and the same loopback guard as every other route here.
2070
- fiber.effect(() => webServer.register({
2071
- kind: 'exact',
2072
- path: `${ROUTE_PREFIX}/browse`,
2073
- handler: async (req, res) => {
2074
- if (!guard(req, res)) return
2075
- if (req.method !== 'POST') {
2076
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2077
- return
2078
- }
2079
- let body = {}
2080
- try {
2081
- const raw = await readBody(req)
2082
- if (raw) body = JSON.parse(raw)
2083
- } catch {
2084
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2085
- return
2086
- }
2087
- try {
2088
- const listing = await listDirectories(body.path)
2089
- sendJson(res, 200, { ok: true, ...listing })
2090
- } catch (error) {
2091
- const status = error instanceof HttpError ? error.status : 500
2092
- const code = error instanceof HttpError ? error.code : 'internal'
2093
- sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2094
- }
2095
- },
2096
- }))
2097
-
2098
- // The subagent sessions behind one conversation. A subagent is a session of
2099
- // its own, linked only by `parentSession`, so the dialog needs this list
2100
- // before it can offer anything to tick.
2101
- fiber.effect(() => webServer.register({
2102
- kind: 'exact',
2103
- path: `${ROUTE_PREFIX}/children`,
2104
- handler: async (req, res) => {
2105
- if (!guard(req, res)) return
2106
- if (req.method !== 'POST') {
2107
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2108
- return
2109
- }
2110
- let body = {}
2111
- try {
2112
- const raw = await readBody(req)
2113
- if (raw) body = JSON.parse(raw)
2114
- } catch {
2115
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2116
- return
2117
- }
2118
- const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
2119
- if (!SESSION_ID_RE.test(sessionId)) {
2120
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'invalid session id' })
2121
- return
2122
- }
2123
- try {
2124
- const headers = await listSessionHeaders(ctx)
2125
- sendJson(res, 200, { ok: true, children: describeChildren(headers, sessionId) })
2126
- } catch (error) {
2127
- const status = error instanceof HttpError ? error.status : 500
2128
- const code = error instanceof HttpError ? error.code : 'internal'
2129
- sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2130
- }
2131
- },
2132
- }))
2133
- fiber.effect(() => webServer.register({
2134
- kind: 'exact',
2135
- path: `${ROUTE_PREFIX}/delete`,
2136
- handler: async (req, res) => {
2137
- if (!guard(req, res)) return
2138
- if (req.method !== 'POST') {
2139
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2140
- return
2141
- }
2142
- let body = {}
2143
- try {
2144
- const raw = await readBody(req)
2145
- if (raw) body = JSON.parse(raw)
2146
- } catch {
2147
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2148
- return
2149
- }
2150
- const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
2151
- if (!sessionId) {
2152
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'sessionId required' })
2153
- return
2154
- }
2155
- try {
2156
- // Validate before touching anything: the quarantine runs first, so an
2157
- // unchecked id would reach the filesystem ahead of deleteSession's own
2158
- // guard. `/artifacts` already validates at the same point.
2159
- if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
2160
- // Quarantine first: the session log is still there to derive the plan
2161
- // from, and a partial move leaves the conversation intact to retry.
2162
- const wantsQuarantine = typeof body.quarantine === 'object' && body.quarantine !== null
2163
- // The plan handed to the move must honour the same `skipGit` the dialog
2164
- // listed, or a file the listing refused to show would move anyway.
2165
- const plan = wantsQuarantine
2166
- ? await planArtifacts(ctx, sessionId, undefined, { skipGit: body.quarantine.skipGit === true })
2167
- : null
2168
- const quarantine = await runQuarantine(ctx, sessionId, body.quarantine, plan)
2169
- const result = await deleteSession(ctx, sessionId, {
2170
- recycle: body.recycle !== false,
2171
- childSessionIds: Array.isArray(body.childSessionIds) ? body.childSessionIds : [],
2172
- })
2173
- sendJson(res, 200, quarantine === null ? { ok: true, ...result } : { ok: true, ...result, quarantine })
2174
- } catch (error) {
2175
- const status = error instanceof HttpError ? error.status : 500
2176
- const code = error instanceof HttpError ? error.code : 'internal'
2177
- sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2178
- }
2179
- },
2180
- }))
2181
-
2182
- fiber.effect(() => webServer.register({
2183
- kind: 'exact',
2184
- path: `${ROUTE_PREFIX}/delete-many`,
2185
- handler: async (req, res) => {
2186
- if (!guard(req, res)) return
2187
- if (req.method !== 'POST') {
2188
- sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2189
- return
2190
- }
2191
- let body = {}
2192
- try {
2193
- const raw = await readBody(req)
2194
- if (raw) body = JSON.parse(raw)
2195
- } catch {
2196
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2197
- return
2198
- }
2199
- const sessionIds = Array.isArray(body.sessionIds)
2200
- ? [...new Set(body.sessionIds.filter((id) => typeof id === 'string' && id.trim()).map((id) => id.trim()))]
2201
- : []
2202
- if (sessionIds.length === 0) {
2203
- sendJson(res, 400, { ok: false, code: 'invalid', error: 'sessionIds required' })
2204
- return
2205
- }
2206
- if (sessionIds.length > MAX_BATCH) {
2207
- sendJson(res, 400, { ok: false, code: 'invalid', error: `too many sessions (max ${MAX_BATCH})` })
2208
- return
2209
- }
2210
- // Bounded-concurrency batch: every item runs the same guarded pipeline
2211
- // (lease retry, directory sweep, workspace accounting); independent
2212
- // sessions run in parallel and the workspace accounting mutation is
2213
- // serialized inside deleteSession, so a batch can never interleave two
2214
- // deletions of the same storage.
2215
- const results = await deleteSessions(ctx, sessionIds, {
2216
- recycle: body.recycle !== false,
2217
- childSessionIds: Array.isArray(body.childSessionIds) ? body.childSessionIds : [],
2218
- })
2219
- const deleted = results.filter((item) => item.ok).length
2220
- sendJson(res, 200, { ok: true, results, deleted, failed: results.length - deleted })
2221
- },
2222
- }))
2223
- }
2224
-
2225
- const webServer = ctx.get('webServer')
2226
- if (webServer) {
2227
- registerRoutes(webServer, ctx)
2228
- } else {
2229
- // A terminal-only profile never provides a web surface; register once one
2230
- // appears instead of waiting on a service that will never arrive.
2231
- ctx.inject(['webServer'], (sub) => registerRoutes(sub.webServer, sub))
2232
- }
2233
- }
2234
-
2235
- // Re-exported for the offline test suite, which drives the artifact plan and the
2236
- // quarantine against a scratch tree and a stubbed persistence service. Nothing
2237
- // else in the host reads this face.
2238
- export const internals = {
2239
- pickFolder,
2240
- artifactCandidates,
2241
- assertListedPath,
2242
- removeOneFile,
2243
- claimQuarantineDirectory,
2244
- classifyPaths,
2245
- collectSessionPaths,
2246
- MAX_SCANNED,
2247
- findSessionCaches,
2248
- freeDestination,
2249
- identityKey,
2250
- insidePath,
2251
- listDirectories,
2252
- moveToSessionTrash,
2253
- planArtifacts,
2254
- quarantineFiles,
2255
- resolveQuarantineRoot,
2256
- removeForever,
2257
- deleteSession,
2258
- deleteSessions,
2259
- busyBackoff,
2260
- BUSY_RETRY_ATTEMPTS,
2261
- retirePaths,
2262
- retireTargets,
2263
- listSessionHeaders,
2264
- collectOrphans,
2265
- collectDescendants,
2266
- bareSessionId,
2267
- describeChildren,
2268
- selectChildDeletes,
2269
- runQuarantine,
2270
- sendToRecycleBin,
2271
- toolTarget,
2272
- trashCommandFor,
2273
- warmCompiledHelpers,
2274
- }
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
+ // A live session is the common case: detaching releases the write lease through
642
+ // an asynchronous retirement, so the FIRST probe almost always finds it busy.
643
+ // A flat 200ms delay therefore charged every live delete ~200ms before it even
644
+ // started. The wait is now exponential — 20, 40, 80, 160, then the old 200ms —
645
+ // which lands the typical case in ~20-40ms and keeps the ceiling unchanged
646
+ // (total wait is shorter than 12 x 200ms, never longer).
647
+ const BUSY_RETRY_ATTEMPTS = 12
648
+ const BUSY_RETRY_BASE_MS = 20
649
+ const BUSY_RETRY_MAX_MS = 200
650
+
651
+ /**
652
+ * How long to wait before retry `attempt` (1-based).
653
+ * @param attempt - the retry about to happen.
654
+ * @returns milliseconds to sleep.
655
+ */
656
+ function busyBackoff(attempt) {
657
+ const step = BUSY_RETRY_BASE_MS * 2 ** Math.max(0, attempt - 1)
658
+ return Math.min(step, BUSY_RETRY_MAX_MS)
659
+ }
660
+
661
+ function sleep(ms) {
662
+ return new Promise((resolve) => setTimeout(resolve, ms))
663
+ }
664
+
665
+ async function assertNoActiveWriter(ctx, sessionId) {
666
+ const sp = ctx.get('sessionPersistence')
667
+ if (!sp || typeof sp.open !== 'function') return false
668
+ for (let attempt = 1; attempt <= BUSY_RETRY_ATTEMPTS; attempt += 1) {
669
+ let handle = null
670
+ let busy = false
671
+ try {
672
+ handle = await sp.open(sessionId, 'write')
673
+ } catch (error) {
674
+ const message = String((error && error.message) || error)
675
+ if (/own|busy|lock|hold|writer/i.test(message)) {
676
+ busy = true
677
+ } else {
678
+ return false
679
+ }
680
+ } finally {
681
+ try {
682
+ if (handle && typeof handle.close === 'function') await handle.close()
683
+ } catch {
684
+ // lease release failure is harmless: the directory is removed next
685
+ }
686
+ }
687
+ if (!busy) return true
688
+ if (attempt < BUSY_RETRY_ATTEMPTS) await sleep(busyBackoff(attempt))
689
+ }
690
+ throw new HttpError(409, 'busy', 'session is currently open in DSH')
691
+ }
692
+
693
+ // Bounded concurrency for batch deletes. Different sessions are independent
694
+ // (agent quiesce, lease probe and directory sweep all key off the session id),
695
+ // so the pipeline runs in parallel through a small pool. The one shared
696
+ // mutation - workspace accounting - is serialized through withWorkspaceLock so
697
+ // two deletions can never interleave on the same store.
698
+ //
699
+ // 6 is measured, not guessed: on 64 sessions of ~2MB the wall time was
700
+ // 281ms at 4, 189ms at 6 and 142ms at 8 (the I/O parallelism saturates around
701
+ // 8), so 6 keeps a ~33% gain over 4 while staying below the saturation knee
702
+ // and limiting the number of simultaneous lease-probe loops.
703
+ const BATCH_CONCURRENCY = 6
704
+ // The lease probe is a few milliseconds of waiting, not I/O: it can run wider
705
+ // than the file sweep without adding load, and that width is the whole point of
706
+ // phase 2 of the batch pipeline.
707
+ const BATCH_PROBE_CONCURRENCY = 16
708
+
709
+ let workspaceLock = Promise.resolve()
710
+ function withWorkspaceLock(fn) {
711
+ const run = workspaceLock.then(fn, fn)
712
+ workspaceLock = run.then(() => undefined, () => undefined)
713
+ return run
714
+ }
715
+
716
+ async function runWithConcurrency(items, limit, worker) {
717
+ const results = new Array(items.length)
718
+ let cursor = 0
719
+ const runners = []
720
+ for (let i = 0; i < Math.min(limit, items.length); i += 1) {
721
+ runners.push((async () => {
722
+ while (true) {
723
+ const index = cursor
724
+ cursor += 1
725
+ if (index >= items.length) return
726
+ results[index] = await worker(items[index], index)
727
+ }
728
+ })())
729
+ }
730
+ await Promise.all(runners)
731
+ return results
732
+ }
733
+
734
+ async function detachFromWorkspace(ctx, sessionId) {
735
+ const workspace = ctx.get('workspaceRegistry')
736
+ if (!workspace) return false
737
+ const variants = idVariants(sessionId)
738
+ let touched = false
739
+ try {
740
+ if (typeof workspace.list === 'function') {
741
+ for (const entry of workspace.list()) {
742
+ if (!entry || !Array.isArray(entry.sessionIds)) continue
743
+ if (!variants.some((variant) => entry.sessionIds.includes(variant))) continue
744
+ try {
745
+ await entry.detachSession(sessionId)
746
+ touched = true
747
+ } catch {
748
+ // keep going: the header index cleanup below still applies
749
+ }
750
+ }
751
+ }
752
+ } catch {
753
+ // registry unavailable
754
+ }
755
+ try {
756
+ if (workspace.sessionPaths && typeof workspace.sessionPaths.delete === 'function') {
757
+ for (const variant of variants) workspace.sessionPaths.delete(variant)
758
+ }
759
+ } catch {
760
+ // private map absent on this version
761
+ }
762
+ try {
763
+ if (workspace.headers && typeof workspace.headers.delete === 'function') {
764
+ for (const variant of variants) workspace.headers.delete(variant)
765
+ }
766
+ } catch {
767
+ // private map absent on this version
768
+ }
769
+ return touched
770
+ }
771
+
772
+ // --- core delete -------------------------------------------------------------
773
+
774
+ /**
775
+ * Phase 1 - stop everything that writes to a session and flush its log.
776
+ * Cheap and independent per session, so a batch runs these together.
777
+ */
778
+ async function stopSession(ctx, sessionId) {
779
+ await quiesceAgent(ctx, sessionId)
780
+ return flushAndDetach(ctx, sessionId)
781
+ }
782
+
783
+ /** Phase 2 - wait for the write lease. The waits of different sessions overlap. */
784
+ async function requireWritable(ctx, sessionId) {
785
+ await assertNoActiveWriter(ctx, sessionId)
786
+ }
787
+
788
+ /**
789
+ * Phase 3 - retire the files, verify, drop the workspace accounting, then take
790
+ * the ticked child sessions with it.
791
+ *
792
+ * Children stay sequential and last: one failure never takes the parent result
793
+ * down with it, because the parent is what the user clicked.
794
+ *
795
+ * @returns `{ removed, caches, workspaceDetached, children }`.
796
+ */
797
+ async function retireSession(ctx, sessionId, options, stopResult) {
798
+ const recycle = options === undefined || options === null || options.recycle !== false
799
+ const childSessionIds = options !== undefined && options !== null && Array.isArray(options.childSessionIds)
800
+ ? options.childSessionIds
801
+ .filter((id) => typeof id === 'string' && SESSION_ID_RE.test(id))
802
+ .filter((id) => bareSessionId(id) !== bareSessionId(sessionId))
803
+ : []
804
+ const flushed = stopResult !== undefined && stopResult !== null && stopResult.flushed === true
805
+ const detached = stopResult !== undefined && stopResult !== null && stopResult.detached === true
806
+
807
+ const { removed, caches } = await retireSessionFiles(sessionId, recycle)
808
+
809
+ const sp = ctx.get('sessionPersistence')
810
+ if (sp && typeof sp.stat === 'function') {
811
+ const after = await sp.stat(sessionId).catch(() => undefined)
812
+ if (after) {
813
+ throw new HttpError(500, 'verify-failed', 'session is still visible to the persistence service after deletion')
814
+ }
815
+ }
816
+ const leftover = findSessionDirs(sessionId)
817
+ if (leftover.length > 0) {
818
+ throw new HttpError(500, 'verify-failed', 'session directories could not be fully removed')
819
+ }
820
+
821
+ const workspaceDetached = await withWorkspaceLock(() => detachFromWorkspace(ctx, sessionId))
822
+ if (removed === 0 && !workspaceDetached && !flushed && !detached && caches === 0) {
823
+ throw new HttpError(404, 'not-found', 'session not found')
824
+ }
825
+
826
+ const children = []
827
+ for (const childId of childSessionIds) {
828
+ try {
829
+ // A subagent can still be running while its parent is deleted. Removing the
830
+ // log out from under it is what made the agent's next write fail with ENOENT,
831
+ // so a child gets the same guard as the parent: stop it, flush it, and wait
832
+ // for the write lease before a single byte moves.
833
+ await quiesceAgent(ctx, childId)
834
+ await flushAndDetach(ctx, childId)
835
+ await assertNoActiveWriter(ctx, childId)
836
+ const childFiles = await retireSessionFiles(childId, recycle)
837
+ await withWorkspaceLock(() => detachFromWorkspace(ctx, childId))
838
+ children.push({ id: childId, removed: childFiles.removed, caches: childFiles.caches })
839
+ } catch (error) {
840
+ // Never delete a child that could not be quieted: something is still writing
841
+ // to it. Report it so the caller can try again once it settles.
842
+ const busy = error instanceof HttpError && error.code === 'busy'
843
+ children.push({
844
+ id: childId,
845
+ removed: 0,
846
+ caches: 0,
847
+ skipped: busy ? 'busy' : 'error',
848
+ error: String((error && error.message) || error),
849
+ })
850
+ }
851
+ }
852
+
853
+ return { removed, caches, workspaceDetached, children }
854
+ }
855
+
856
+ /**
857
+ * Delete one session: the three phases in order. Kept as the single-session
858
+ * entry point, and expressed in the same phase helpers the batch uses so the two
859
+ * can never drift apart.
860
+ */
861
+ async function deleteSession(ctx, sessionId, options) {
862
+ if (!SESSION_ID_RE.test(sessionId)) {
863
+ throw new HttpError(400, 'invalid', 'invalid session id')
864
+ }
865
+ const stopResult = await stopSession(ctx, sessionId)
866
+ await requireWritable(ctx, sessionId)
867
+ const result = await retireSession(ctx, sessionId, options, stopResult)
868
+ return {
869
+ removed: result.removed,
870
+ caches: result.caches,
871
+ stopped: stopResult !== undefined && stopResult.flushed !== undefined,
872
+ flushed: stopResult.flushed,
873
+ detached: stopResult.detached,
874
+ workspaceDetached: result.workspaceDetached,
875
+ children: result.children,
876
+ }
877
+ }
878
+
879
+ /**
880
+ * Delete many sessions as three overlapping phases:
881
+ *
882
+ * 1. stop and flush every session (bounded, but the work is tiny)
883
+ * 2. probe every write lease (wide: these are the 20-40ms waits, and they only
884
+ * overlap if nothing queues behind the retire workers)
885
+ * 3. retire files, verify, detach accounting, take children (bounded)
886
+ *
887
+ * The old shape ran all three phases inside each session, six at a time, so a
888
+ * batch of live sessions paid its lease waits in waves. One failing session never
889
+ * takes the batch down: it comes back as `{ ok: false }`.
890
+ *
891
+ * @returns one `{ sessionId, ok, removed }` (or `{ ok: false, code, error }`) per id.
892
+ */
893
+ async function deleteSessions(ctx, sessionIds, options) {
894
+ const valid = []
895
+ const rejected = []
896
+ for (const sessionId of sessionIds) {
897
+ if (SESSION_ID_RE.test(sessionId)) valid.push(sessionId)
898
+ else rejected.push({ sessionId, ok: false, code: 'invalid', error: 'invalid session id' })
899
+ }
900
+
901
+ // Phase 1: stop + flush. A failure here is that session's failure only.
902
+ const stopped = new Map()
903
+ const stopErrors = new Map()
904
+ await runWithConcurrency(valid, BATCH_CONCURRENCY, async (sessionId) => {
905
+ try {
906
+ stopped.set(sessionId, await stopSession(ctx, sessionId))
907
+ } catch (error) {
908
+ stopErrors.set(sessionId, error)
909
+ }
910
+ })
911
+
912
+ // Phase 2: lease probe, wide. Sessions that never stopped are not probed.
913
+ const unready = new Map()
914
+ const ready = valid.filter((sessionId) => !stopErrors.has(sessionId))
915
+ await runWithConcurrency(ready, BATCH_PROBE_CONCURRENCY, async (sessionId) => {
916
+ try {
917
+ await requireWritable(ctx, sessionId)
918
+ } catch (error) {
919
+ unready.set(sessionId, error)
920
+ }
921
+ })
922
+
923
+ // Phase 3: retire what is clear to go.
924
+ const results = []
925
+ const swept = valid.filter((sessionId) => !stopErrors.has(sessionId) && !unready.has(sessionId))
926
+ const retired = new Map()
927
+ const retireErrors = new Map()
928
+ await runWithConcurrency(swept, BATCH_CONCURRENCY, async (sessionId) => {
929
+ try {
930
+ retired.set(sessionId, await retireSession(ctx, sessionId, options, stopped.get(sessionId)))
931
+ } catch (error) {
932
+ retireErrors.set(sessionId, error)
933
+ }
934
+ })
935
+
936
+ for (const sessionId of valid) {
937
+ const error = stopErrors.get(sessionId) || unready.get(sessionId) || retireErrors.get(sessionId)
938
+ if (error !== undefined) {
939
+ results.push({
940
+ sessionId,
941
+ ok: false,
942
+ code: error instanceof HttpError ? error.code : 'internal',
943
+ error: String((error && error.message) || error),
944
+ })
945
+ continue
946
+ }
947
+ results.push({ sessionId, ok: true, removed: retired.get(sessionId).removed })
948
+ }
949
+
950
+ return [...results, ...rejected]
951
+ }
952
+ /**
953
+ * Take one session off the disk: its directories and its cache rows, then any
954
+ * directory the drain recreated. Shared by the parent and every child, so a
955
+ * subagent is retired exactly like the conversation the user clicked.
956
+ *
957
+ * @returns how many paths went away, and how many cache rows are now gone.
958
+ */
959
+ async function retireSessionFiles(sessionId, recycle) {
960
+ const cacheFiles = findSessionCaches(sessionId)
961
+ const targets = [...findSessionDirs(sessionId), ...cacheFiles]
962
+ let gone = await retireTargets(targets, recycle)
963
+ await new Promise((resolve) => setImmediate(resolve))
964
+ gone = gone.concat(await retireTargets(findSessionDirs(sessionId), recycle))
965
+ return { removed: gone.length, caches: cacheFiles.filter((file) => !fs.existsSync(file)).length }
966
+ }
967
+
968
+ // --- artifacts: what a session touched, and quarantining it -----------------
969
+ //
970
+ // "Produced files" is derived from the durable session log alone: the log is the
971
+ // only record that outlives a closed Session (the host's own observation state
972
+ // lives in a plugin-local WeakMap and dies with the process, and the
973
+ // `workspace/changes` summaries live in a temporary directory that disposal
974
+ // removes). Classification rests on one invariant of the default
975
+ // fs-observation-policy: `write` may not overwrite a file that was not read
976
+ // first, and `edit` requires a prior read. So a write whose path has no earlier
977
+ // successful read CREATED the file; anything else already existed.
978
+ //
979
+ // Nothing here deletes. Files are moved into a timestamped quarantine directory
980
+ // under $DSH_HOME, keeping their path relative to the session's working
981
+ // directory, so a wrong call is recoverable.
982
+
983
+ const QUARANTINE_PREFIX = 'purge-quarantine'
984
+ const MAX_LISTED = 500
985
+ /**
986
+ * How many distinct paths one scan will resolve. Every path costs a realpath,
987
+ * and a session that walked a large tree can name tens of thousands of them;
988
+ * the dialog would sit on "scanning" for as long as they take. Past this the
989
+ * plan reports `truncated`, which the dialog already surfaces.
990
+ */
991
+ const MAX_SCANNED = 2000
992
+ /** How many path resolutions run at once: enough to hide the threadpool round trip, few enough to stay polite. */
993
+ const RESOLVE_CONCURRENCY = 16
994
+ /** How many directories the folder picker lists before saying there are more. */
995
+ const MAX_BROWSE_ENTRIES = 500
996
+ /** How long the OS chooser may stay open before the request gives up on it. */
997
+ const PICK_TIMEOUT_MS = 5 * 60 * 1000
998
+ /** How long a shell helper (the recycle-bin script) may run before giving up. */
999
+ const SHELL_TIMEOUT_MS = 5 * 60 * 1000
1000
+
1001
+ /** Run a program and collect its output, leaving the meaning of the exit to the caller. */
1002
+ function runExecutable(program, args, timeoutMs) {
1003
+ return new Promise((resolve, reject) => {
1004
+ const child = spawn(program, args, { windowsHide: true })
1005
+ let out = ''
1006
+ let err = ''
1007
+ let settled = false
1008
+ const finish = (fn, value) => {
1009
+ if (settled) return
1010
+ settled = true
1011
+ clearTimeout(timer)
1012
+ fn(value)
1013
+ }
1014
+ const timer = setTimeout(() => {
1015
+ try { child.kill() } catch { /* already gone */ }
1016
+ finish(reject, new HttpError(504, 'timeout', '等待系统对话框超时'))
1017
+ }, timeoutMs)
1018
+
1019
+ child.stdout.on('data', (chunk) => { out += chunk.toString('utf8') })
1020
+ child.stderr.on('data', (chunk) => { err += chunk.toString('utf8') })
1021
+ child.on('error', (error) => {
1022
+ finish(reject, new HttpError(500, 'spawn', `无法启动 ${path.basename(program)}:${String((error && error.message) || error)}`))
1023
+ })
1024
+ child.on('close', (code) => finish(resolve, { code, stdout: out, stderr: err }))
1025
+ })
1026
+ }
1027
+
1028
+ /** Argument keys carrying the target path, per writing tool. */
1029
+ const WRITE_TOOL_PATHS = {
1030
+ write: ['file_path', 'path'],
1031
+ edit: ['file_path', 'path'],
1032
+ str_replace_editor: ['path', 'file_path'],
1033
+ create_file: ['file_path', 'path'],
1034
+ }
1035
+
1036
+ /** Argument keys carrying the target path, per reading tool. */
1037
+ const READ_TOOL_PATHS = {
1038
+ read: ['file_path', 'path'],
1039
+ read_file: ['file_path', 'path'],
1040
+ }
1041
+
1042
+ /**
1043
+ * Resolve the target path one tool call names.
1044
+ * @param name - tool name.
1045
+ * @param argumentsJson - the model's raw argument JSON.
1046
+ * @param cwd - the session's recorded working directory, for relative paths.
1047
+ * @returns the absolute path and whether the tool writes, or undefined.
1048
+ */
1049
+ function toolTarget(name, argumentsJson, cwd) {
1050
+ const writes = Object.prototype.hasOwnProperty.call(WRITE_TOOL_PATHS, name)
1051
+ const keys = writes ? WRITE_TOOL_PATHS[name] : READ_TOOL_PATHS[name]
1052
+ if (keys === undefined) return undefined
1053
+ let args
1054
+ try {
1055
+ args = JSON.parse(typeof argumentsJson === 'string' ? argumentsJson : '')
1056
+ } catch {
1057
+ return undefined
1058
+ }
1059
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) return undefined
1060
+ const raw = keys.map((key) => args[key]).find((value) => typeof value === 'string' && value.trim() !== '')
1061
+ if (raw === undefined) return undefined
1062
+ let absolute
1063
+ if (path.isAbsolute(raw)) absolute = raw
1064
+ else if (cwd === undefined) return undefined
1065
+ else absolute = path.resolve(cwd, raw)
1066
+ return { path: absolute, writes }
1067
+ }
1068
+
1069
+ /** Read a stored session's events through the persistence seam. */
1070
+ async function readSessionEvents(ctx, sessionId) {
1071
+ const sp = ctx.get('sessionPersistence')
1072
+ if (!sp || typeof sp.open !== 'function') {
1073
+ return { events: [], warning: '持久化服务不可用,无法读取会话日志' }
1074
+ }
1075
+ let handle = null
1076
+ try {
1077
+ handle = await sp.open(sessionId, 'read')
1078
+ const result = await handle.read()
1079
+ const events = Array.isArray(result && result.events) ? result.events : []
1080
+ return { events, warning: undefined }
1081
+ } catch (error) {
1082
+ return { events: [], warning: `读取会话日志失败:${String((error && error.message) || error)}` }
1083
+ } finally {
1084
+ try {
1085
+ if (handle && typeof handle.close === 'function') await handle.close()
1086
+ } catch {
1087
+ // a close failure must not change the plan
1088
+ }
1089
+ }
1090
+ }
1091
+
1092
+ /**
1093
+ * Identity of one path for "have we seen this file before?" purposes. The real
1094
+ * path when it resolves, so a symlink alias and its target count as the same
1095
+ * file; otherwise a case-folded resolved path on Windows, whose filesystem does
1096
+ * not distinguish `Foo.md` from `foo.md`. Comparing spellings instead would let
1097
+ * a write through an alias look like a creation.
1098
+ * @param absolute - the path a tool call named.
1099
+ * @param cache - optional per-scan memo; without it the resolution cost scales
1100
+ * with log length rather than with the number of distinct files.
1101
+ * @returns a stable key for the file, not for the spelling.
1102
+ */
1103
+ async function identityKey(absolute, cache) {
1104
+ if (cache !== undefined) {
1105
+ const hit = cache.get(absolute)
1106
+ if (hit !== undefined) return hit
1107
+ }
1108
+ let key
1109
+ try {
1110
+ key = await realpathNative(absolute)
1111
+ } catch {
1112
+ const resolved = path.resolve(absolute)
1113
+ key = process.platform === 'win32' ? resolved.toLowerCase() : resolved
1114
+ }
1115
+ if (cache !== undefined) cache.set(absolute, key)
1116
+ return key
1117
+ }
1118
+
1119
+ /**
1120
+ * Every path this session's writing tools touched, split by whether the session
1121
+ * created it or found it already there.
1122
+ * @param events - stored session events, in order.
1123
+ * @param cwd - the session's recorded working directory.
1124
+ * @param cache - optional per-scan memo for path resolution, shared across calls.
1125
+ * @returns `{ created, modified }`, keyed by file identity, each row `{ path, identity, ops }`.
1126
+ */
1127
+ async function collectSessionPaths(events, cwd, cache) {
1128
+ const pending = new Map()
1129
+ const read = new Set()
1130
+ const created = new Map()
1131
+ const modified = new Map()
1132
+ const memo = cache !== undefined ? cache : new Map()
1133
+
1134
+ // Resolve every distinct path the log names first, together. A long session
1135
+ // names the same handful of files thousands of times, so awaiting per call
1136
+ // would buy one threadpool round trip per mention; this buys one per file.
1137
+ const named = new Set()
1138
+ let overflow = false
1139
+ for (const event of events) {
1140
+ const data = event && event.data
1141
+ if (!data || typeof data !== 'object' || event.type !== 'tool/call') continue
1142
+ const target = toolTarget(typeof data.name === 'string' ? data.name : '', data.arguments, cwd)
1143
+ if (target === undefined) continue
1144
+ if (named.size >= MAX_SCANNED && !named.has(target.path)) {
1145
+ overflow = true
1146
+ break
1147
+ }
1148
+ named.add(target.path)
1149
+ }
1150
+ await runWithConcurrency([...named], RESOLVE_CONCURRENCY, async (absolute) => {
1151
+ await identityKey(absolute, memo)
1152
+ })
1153
+
1154
+ const commit = (call) => {
1155
+ // A file the session created and later edited stays "created": one identity
1156
+ // must never sit in both buckets, or a scope=all run would target it twice
1157
+ // and report a spurious failure for the second attempt.
1158
+ const alreadyCreated = created.get(call.identity)
1159
+ if (alreadyCreated !== undefined) {
1160
+ alreadyCreated.ops += 1
1161
+ return
1162
+ }
1163
+ const bucket = call.existedBefore ? modified : created
1164
+ const prior = bucket.get(call.identity)
1165
+ if (prior !== undefined) prior.ops += 1
1166
+ else bucket.set(call.identity, { path: call.path, identity: call.identity, ops: 1 })
1167
+ }
1168
+
1169
+ for (const event of events) {
1170
+ const data = event && event.data
1171
+ if (!data || typeof data !== 'object') continue
1172
+
1173
+ if (event.type === 'tool/call') {
1174
+ const name = typeof data.name === 'string' ? data.name : ''
1175
+ const target = toolTarget(name, data.arguments, cwd)
1176
+ // Existence is decided at call time, against the reads that already
1177
+ // succeeded - the policy's own ordering - and on identity, so an alias of
1178
+ // a file the session read is still an edit.
1179
+ if (target !== undefined) {
1180
+ const identity = await identityKey(target.path, memo)
1181
+ pending.set(data.callId, {
1182
+ path: target.path,
1183
+ identity,
1184
+ writes: target.writes,
1185
+ existedBefore: read.has(identity),
1186
+ })
1187
+ }
1188
+ continue
1189
+ }
1190
+
1191
+ if (event.type !== 'tool/result') continue
1192
+ const message = data.message
1193
+ const callId = message && typeof message.toolCallId === 'string' ? message.toolCallId : undefined
1194
+ if (callId === undefined) continue
1195
+ const call = pending.get(callId)
1196
+ if (call === undefined) continue
1197
+ pending.delete(callId)
1198
+ if (data.error !== undefined || (message && message.isError === true)) continue
1199
+ if (call.writes) commit(call)
1200
+ else read.add(call.identity)
1201
+ }
1202
+
1203
+ return { named: named.size, overflow, created, modified }
1204
+ }
1205
+
1206
+ /**
1207
+ * Whether `child` is strictly inside `parent`, comparing real paths. Folded on
1208
+ * Windows, where the filesystem ignores case: a realpath does not normalise the
1209
+ * case of a prefix that still matches a differently-spelled spelling.
1210
+ */
1211
+ function insidePath(parent, child) {
1212
+ if (parent === child) return false
1213
+ const fold = (value) => (process.platform === 'win32' ? value.toLowerCase() : value)
1214
+ const base = fold(parent)
1215
+ const prefix = base.endsWith(path.sep) ? base : base + path.sep
1216
+ return fold(child).startsWith(prefix)
1217
+ }
1218
+
1219
+ /**
1220
+ * Is this directory inside a git working tree? A `.git` entry marks the root —
1221
+ * a directory in a normal clone, a file in a worktree or a submodule.
1222
+ *
1223
+ * The walk memoises per directory: one plan can span hundreds of files that share
1224
+ * a handful of folders, and each miss would otherwise stat every level again.
1225
+ */
1226
+ async function isInsideGitRepo(directory, cache) {
1227
+ let current = path.resolve(directory)
1228
+ const walked = []
1229
+ for (;;) {
1230
+ if (cache.has(current)) {
1231
+ const verdict = cache.get(current)
1232
+ for (const dir of walked) cache.set(dir, verdict)
1233
+ return verdict
1234
+ }
1235
+ walked.push(current)
1236
+ try {
1237
+ const marker = await fsp.stat(path.join(current, '.git'))
1238
+ if (marker.isDirectory() || marker.isFile()) {
1239
+ for (const dir of walked) cache.set(dir, true)
1240
+ return true
1241
+ }
1242
+ } catch {
1243
+ // no .git here; keep walking up
1244
+ }
1245
+ const parent = path.dirname(current)
1246
+ if (parent === current) {
1247
+ for (const dir of walked) cache.set(dir, false)
1248
+ return false
1249
+ }
1250
+ current = parent
1251
+ }
1252
+ }
1253
+
1254
+ /**
1255
+ * Keep only the paths that may actually be moved: an existing regular file whose
1256
+ * real path is strictly inside the session's working directory and outside the
1257
+ * DSH home. Every rejection carries its reason.
1258
+ * @param rows - candidate rows `{ path, ops }`.
1259
+ * @param cwd - the session's recorded working directory.
1260
+ * @param home - resolved DSH home.
1261
+ * @param options - `{ skipGit }`: also refuse files inside a git working tree.
1262
+ * @returns `{ allowed, refused }`.
1263
+ */
1264
+ async function classifyPaths(rows, cwd, home, options) {
1265
+ const allowed = []
1266
+ const refused = []
1267
+ const skipGit = options !== undefined && options !== null && options.skipGit === true
1268
+ const gitCache = new Map()
1269
+ const list = [...rows.values()]
1270
+ if (cwd === undefined) {
1271
+ for (const row of list) refused.push({ path: row.path, reason: '会话未记录工作目录,无法安全定位' })
1272
+ return { allowed, refused }
1273
+ }
1274
+ let realCwd
1275
+ try {
1276
+ realCwd = await fsp.realpath(cwd)
1277
+ } catch {
1278
+ for (const row of list) refused.push({ path: row.path, reason: '会话工作目录已不存在,无法校验归属' })
1279
+ return { allowed, refused }
1280
+ }
1281
+ let realHome = home
1282
+ try {
1283
+ realHome = await fsp.realpath(home)
1284
+ } catch {
1285
+ // an absent home cannot contain anything that exists
1286
+ }
1287
+ // Resolve each row's stat and real path together rather than one after another:
1288
+ // a long session can list hundreds of files, and awaiting them serially turns
1289
+ // one threadpool round trip into hundreds. `runWithConcurrency` keeps the order.
1290
+ const verdicts = await runWithConcurrency(list, RESOLVE_CONCURRENCY, async (row) => {
1291
+ let info
1292
+ try {
1293
+ info = await fsp.stat(row.path)
1294
+ } catch {
1295
+ return { refuse: { path: row.path, reason: '文件已不存在' } }
1296
+ }
1297
+ if (!info.isFile()) return { refuse: { path: row.path, reason: '不是普通文件,已跳过' } }
1298
+ let real
1299
+ try {
1300
+ real = await fsp.realpath(row.path)
1301
+ } catch {
1302
+ return { refuse: { path: row.path, reason: '无法解析真实路径,已跳过' } }
1303
+ }
1304
+ if (!insidePath(realCwd, real)) {
1305
+ return { refuse: { path: row.path, reason: '不在该对话的工作目录内,已跳过' } }
1306
+ }
1307
+ if (insidePath(realHome, real)) {
1308
+ return { refuse: { path: row.path, reason: '位于 DSH 数据目录内,已跳过' } }
1309
+ }
1310
+ if (skipGit && await isInsideGitRepo(path.dirname(real), gitCache)) {
1311
+ return { refuse: { path: row.path, reason: '位于 git 仓库内,已跳过' } }
1312
+ }
1313
+ return { allow: { path: real, displayPath: row.path, ops: row.ops, bytes: info.size, mtime: info.mtimeMs } }
1314
+ })
1315
+ for (const verdict of verdicts) {
1316
+ if (verdict.allow !== undefined) allowed.push(verdict.allow)
1317
+ else refused.push(verdict.refuse)
1318
+ }
1319
+ return { allowed, refused }
1320
+ }
1321
+
1322
+ /**
1323
+ * Build the artifact plan for one session.
1324
+ * @param ctx - host plugin context.
1325
+ * @param sessionId - validated session id.
1326
+ * @returns `{ cwd, created, modified, refused, truncated, warnings }`.
1327
+ */
1328
+ async function planArtifacts(ctx, sessionId, cache, options) {
1329
+ const home = dshHome()
1330
+ const warnings = []
1331
+ const sp = ctx.get('sessionPersistence')
1332
+ let cwd
1333
+ if (sp && typeof sp.stat === 'function') {
1334
+ try {
1335
+ const snapshot = await sp.stat(sessionId)
1336
+ let header = null
1337
+ if (snapshot !== null && typeof snapshot === 'object') {
1338
+ header = snapshot.header !== null && typeof snapshot.header === 'object' ? snapshot.header : snapshot
1339
+ }
1340
+ if (header && typeof header.cwd === 'string' && header.cwd !== '') cwd = header.cwd
1341
+ } catch (error) {
1342
+ warnings.push(`未找到该会话的存储记录:${String((error && error.message) || error)}`)
1343
+ }
1344
+ }
1345
+ const { events, warning } = await readSessionEvents(ctx, sessionId)
1346
+ if (warning !== undefined) warnings.push(warning)
1347
+ const scan = await collectSessionPaths(events, cwd, cache)
1348
+ const { created, modified } = scan
1349
+ const createdPlan = await classifyPaths(created, cwd, home, options)
1350
+ const modifiedPlan = await classifyPaths(modified, cwd, home, options)
1351
+ const refused = [...createdPlan.refused, ...modifiedPlan.refused]
1352
+ return {
1353
+ // Stamped so a caller handing this plan back cannot smuggle in another
1354
+ // session's list: runQuarantine refuses a plan that does not belong here.
1355
+ sessionId,
1356
+ cwd,
1357
+ created: createdPlan.allowed.slice(0, MAX_LISTED),
1358
+ modified: modifiedPlan.allowed.slice(0, MAX_LISTED),
1359
+ refused: refused.slice(0, MAX_LISTED),
1360
+ truncated: scan.overflow
1361
+ || createdPlan.allowed.length > MAX_LISTED
1362
+ || modifiedPlan.allowed.length > MAX_LISTED
1363
+ || refused.length > MAX_LISTED,
1364
+ warnings,
1365
+ }
1366
+ }
1367
+
1368
+ /**
1369
+ * Claim a quarantine directory under the DSH home. The name carries second
1370
+ * resolution only, so two deletes can land on the same name; an exclusive mkdir
1371
+ * (never `recursive: true`, which would happily reuse an existing tree) decides
1372
+ * the winner and the loser retries with a suffix. Two runs therefore can never
1373
+ * share a tree, which is what stops one run's file from overwriting another's.
1374
+ * @param home - resolved DSH home.
1375
+ * @returns the claimed directory, or undefined when none could be claimed.
1376
+ */
1377
+ async function claimQuarantineDirectory(home) {
1378
+ // A fresh home has no quarantine root yet; creating it is the only write this
1379
+ // side does outside the quarantine tree, and it keeps a missing home from
1380
+ // turning into a silent "cannot claim" on the very first delete.
1381
+ try {
1382
+ await fsp.mkdir(home, { recursive: true })
1383
+ } catch {
1384
+ return undefined
1385
+ }
1386
+ const base = `${QUARANTINE_PREFIX}-${new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)}`
1387
+ for (let attempt = 0; attempt < 1000; attempt += 1) {
1388
+ const candidate = path.join(home, attempt === 0 ? base : `${base}-${attempt}`)
1389
+ try {
1390
+ await fsp.mkdir(candidate, { recursive: false })
1391
+ return candidate
1392
+ } catch (error) {
1393
+ if (error && error.code === 'EEXIST') continue
1394
+ return undefined
1395
+ }
1396
+ }
1397
+ return undefined
1398
+ }
1399
+
1400
+ /** Whether a path exists, without throwing. */
1401
+ async function pathExists(target) {
1402
+ try {
1403
+ await fsp.access(target)
1404
+ return true
1405
+ } catch {
1406
+ return false
1407
+ }
1408
+ }
1409
+
1410
+ /**
1411
+ * A destination inside the quarantine tree that does not already exist. The
1412
+ * move itself must never overwrite: a quarantine that silently replaced an
1413
+ * earlier copy would destroy the only surviving copy of the file it replaced.
1414
+ * @param directory - claimed quarantine directory.
1415
+ * @param relative - path relative to the session's working directory.
1416
+ * @returns a free absolute path, or undefined when every name was taken.
1417
+ */
1418
+ async function freeDestination(directory, relative) {
1419
+ const first = path.join(directory, relative)
1420
+ if (!(await pathExists(first))) return first
1421
+ const dir = path.dirname(first)
1422
+ const ext = path.extname(first)
1423
+ const stem = path.basename(first, ext)
1424
+ for (let n = 1; n < 10000; n += 1) {
1425
+ const candidate = path.join(dir, `${stem}-${n}${ext}`)
1426
+ if (!(await pathExists(candidate))) return candidate
1427
+ }
1428
+ return undefined
1429
+ }
1430
+
1431
+ /**
1432
+ * Move the chosen files into a timestamped quarantine directory under the DSH
1433
+ * home, preserving each path relative to the session's working directory. Files
1434
+ * are moved, never removed, and an existing quarantine entry is never replaced,
1435
+ * so a wrong call is always recoverable by hand.
1436
+ *
1437
+ * Every step is asynchronous on purpose: a cross-device move copies, and a
1438
+ * synchronous copy inside the request handler would freeze the event loop, which
1439
+ * means every other session's traffic stalls behind one large quarantine.
1440
+ *
1441
+ * @param targets - absolute file paths to move.
1442
+ * @param cwd - the session's recorded working directory.
1443
+ * @param home - resolved DSH home.
1444
+ * @returns `{ directory, moved, failed }`.
1445
+ */
1446
+ async function quarantineFiles(targets, cwd, home) {
1447
+ const moved = []
1448
+ const failed = []
1449
+ if (targets.length === 0) return { directory: null, moved, failed }
1450
+
1451
+ const directory = await claimQuarantineDirectory(home)
1452
+ if (directory === undefined) {
1453
+ for (const target of targets) failed.push({ path: target, error: '无法创建隔离目录' })
1454
+ return { directory: null, moved, failed }
1455
+ }
1456
+
1457
+ let realCwd = cwd
1458
+ if (typeof cwd === 'string') {
1459
+ try {
1460
+ realCwd = await fsp.realpath(cwd)
1461
+ } catch {
1462
+ // keep the recorded spelling; classifyPaths already proved containment
1463
+ }
1464
+ }
1465
+ for (const target of targets) {
1466
+ let relative = path.basename(target)
1467
+ if (typeof realCwd === 'string') {
1468
+ const candidate = path.relative(realCwd, target)
1469
+ if (candidate !== '' && !candidate.startsWith('..') && !path.isAbsolute(candidate)) relative = candidate
1470
+ }
1471
+ try {
1472
+ await fsp.mkdir(path.dirname(path.join(directory, relative)), { recursive: true })
1473
+ const destination = await freeDestination(directory, relative)
1474
+ if (destination === undefined) {
1475
+ failed.push({ path: target, error: '隔离目录内没有可用的目标文件名' })
1476
+ continue
1477
+ }
1478
+ try {
1479
+ await fsp.rename(target, destination)
1480
+ } catch {
1481
+ // A cross-device rename fails; fall back to copy-then-remove. `COPYFILE_EXCL`
1482
+ // keeps the copy from replacing anything that appeared in between.
1483
+ await fsp.copyFile(target, destination, fs.constants.COPYFILE_EXCL)
1484
+ await fsp.rm(target, { force: true })
1485
+ }
1486
+ moved.push({ from: target, to: destination })
1487
+ } catch (error) {
1488
+ failed.push({ path: target, error: String((error && error.message) || error) })
1489
+ }
1490
+ }
1491
+ return { directory, moved, failed }
1492
+ }
1493
+
1494
+ /**
1495
+ * The files one plan actually offered. The per-file delete button sends back a
1496
+ * path from this list, and the route refuses anything else: a request cannot
1497
+ * name a file the user was never shown.
1498
+ *
1499
+ * @param plan - the artifact plan this plugin produced for a session.
1500
+ * @returns every listed path, created and modified alike.
1501
+ */
1502
+ function artifactCandidates(plan) {
1503
+ const out = []
1504
+ for (const group of [plan.created, plan.modified]) {
1505
+ if (!Array.isArray(group)) continue
1506
+ for (const row of group) {
1507
+ if (row !== null && row !== undefined && typeof row.path === 'string') out.push(row.path)
1508
+ }
1509
+ }
1510
+ return out
1511
+ }
1512
+
1513
+ /**
1514
+ * The path a per-file delete may touch: one the plan listed, nothing else.
1515
+ * Without this the button would be a general-purpose delete primitive reachable
1516
+ * from the page.
1517
+ *
1518
+ * @param plan - the artifact plan for the session.
1519
+ * @param target - the path the page asked for.
1520
+ * @returns the resolved path, ready to unlink.
1521
+ */
1522
+ function assertListedPath(plan, target) {
1523
+ const resolved = path.resolve(target)
1524
+ const listed = artifactCandidates(plan).some((candidate) => path.resolve(candidate) === resolved)
1525
+ if (!listed) throw new HttpError(403, 'not-listed', '该文件不在本对话的产出清单里')
1526
+ return resolved
1527
+ }
1528
+
1529
+ /**
1530
+ * Delete one produced file. The destination is the user's call, and the dialog
1531
+ * passes the same preference that governs a conversation delete: to the system
1532
+ * trash, or outright.
1533
+ *
1534
+ * @param target - absolute path of the file.
1535
+ * @param recycle - true to send it to the system recycle bin.
1536
+ * @returns `{ recycled }` describing where it went.
1537
+ */
1538
+ async function removeOneFile(target, recycle) {
1539
+ const resolved = path.resolve(target)
1540
+ let info
1541
+ try {
1542
+ info = await fsp.lstat(resolved)
1543
+ } catch (error) {
1544
+ throw new HttpError(404, 'missing', `文件已不存在:${String((error && error.message) || error)}`)
1545
+ }
1546
+ if (!info.isFile()) throw new HttpError(400, 'not-a-file', '只能删除普通文件')
1547
+ if (recycle === true) {
1548
+ const ok = await sendToRecycleBin([resolved])
1549
+ if (!ok) throw new HttpError(500, 'recycle', '移入回收站失败')
1550
+ return { recycled: true }
1551
+ }
1552
+ try {
1553
+ await fsp.unlink(resolved)
1554
+ } catch (error) {
1555
+ throw new HttpError(500, 'unlink', `删除失败:${String((error && error.message) || error)}`)
1556
+ }
1557
+ return { recycled: false }
1558
+ }
1559
+
1560
+ /**
1561
+ * Quarantine the files one request selected. The candidate set is recomputed
1562
+ * here from the session log and the request's paths are intersected with it, so
1563
+ * a tampered request cannot move anything the user was not shown.
1564
+ * @param ctx - host plugin context.
1565
+ * @param sessionId - validated session id.
1566
+ * @param request - `{ scope, paths }` from the client; undefined asks for none.
1567
+ * @returns the outcome, or null when the request asked for no quarantine.
1568
+ */
1569
+ async function runQuarantine(ctx, sessionId, request, knownPlan) {
1570
+ if (request === undefined || request === null || typeof request !== 'object') return null
1571
+ // Validated here as well as at the route, because `internals` exposes this
1572
+ // function and a direct caller must not be able to skip the check.
1573
+ if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
1574
+ const scope = request.scope === 'all' ? 'all' : 'created'
1575
+ // The same flag the dialog was built with, so a derived set cannot contain a
1576
+ // file the listing refused to show.
1577
+ const skipGit = request.skipGit === true
1578
+ // Re-deriving the plan is the expensive half of a delete; a caller that already
1579
+ // holds it for this session hands it over instead of paying for it twice.
1580
+ const plan = knownPlan === undefined || knownPlan === null
1581
+ ? await planArtifacts(ctx, sessionId, undefined, { skipGit })
1582
+ : knownPlan
1583
+ // A handed-in plan must be this session's plan. The route always derives it
1584
+ // from the same id, but `internals` exposes this function, and a future caller
1585
+ // passing its neighbour's plan would move files the user never saw.
1586
+ if (plan.sessionId !== sessionId) throw new HttpError(400, 'invalid', 'plan does not belong to this session')
1587
+ const candidates = scope === 'all' ? [...plan.created, ...plan.modified] : [...plan.created]
1588
+ const allowed = new Set(candidates.map((row) => row.path))
1589
+ const requested = Array.isArray(request.paths) ? request.paths : null
1590
+ const requestedStrings = requested === null ? null : new Set(requested.filter((value) => typeof value === 'string'))
1591
+ const targets = requested === null
1592
+ ? [...allowed]
1593
+ : [...requestedStrings].filter((value) => allowed.has(value))
1594
+ // Resolve the configured save path before moving a single file: a bad path must
1595
+ // stop the request, not send the files somewhere unintended.
1596
+ const rootInfo = await resolveQuarantineRoot(request.root, plan.cwd)
1597
+ if (rootInfo.error !== undefined) throw new HttpError(400, 'invalid', rootInfo.error)
1598
+ const root = rootInfo.root
1599
+ const outcome = await quarantineFiles(targets, plan.cwd, root)
1600
+ return {
1601
+ scope,
1602
+ directory: outcome.moved.length > 0 ? outcome.directory : null,
1603
+ root,
1604
+ moved: outcome.moved,
1605
+ failed: outcome.failed,
1606
+ candidates: allowed.size,
1607
+ selected: targets.length,
1608
+ dropped: requestedStrings === null ? 0 : requestedStrings.size - targets.length,
1609
+ }
1610
+ }
1611
+
1612
+ /**
1613
+ * Decide which directory the timestamped quarantine folder is created under. An
1614
+ * empty request means the DSH home, which is what every earlier version did.
1615
+ * @param requested - the directory the client asked for, if any.
1616
+ * @param cwd - the session's working directory, used to refuse a "quarantine"
1617
+ * that would only shuffle the files around inside the tree they came from.
1618
+ * @returns `{ root }` or `{ error }`.
1619
+ */
1620
+ async function resolveQuarantineRoot(requested, cwd) {
1621
+ const home = dshHome()
1622
+ if (requested === undefined || requested === null || requested === '') return { root: home }
1623
+ if (typeof requested !== 'string') return { error: '保存路径必须是字符串' }
1624
+ if (requested.length > 4096) return { error: '保存路径过长' }
1625
+ if (!path.isAbsolute(requested)) return { error: '保存路径必须是绝对路径' }
1626
+
1627
+ let real
1628
+ try {
1629
+ real = await fsp.realpath(requested)
1630
+ } catch {
1631
+ return { error: `保存路径不存在:${requested}` }
1632
+ }
1633
+ let info
1634
+ try {
1635
+ info = await fsp.stat(real)
1636
+ } catch {
1637
+ return { error: `无法读取保存路径:${requested}` }
1638
+ }
1639
+ if (!info.isDirectory()) return { error: '保存路径不是目录' }
1640
+
1641
+ // The sessions store belongs to DSH; filling it with quarantined files would
1642
+ // drop them back into the one tree the delete pipeline sweeps.
1643
+ const sessionsRoot = path.join(home, 'sessions')
1644
+ if (real === sessionsRoot || insidePath(sessionsRoot, real)) {
1645
+ return { error: '不能把隔离夹设在会话存储目录内' }
1646
+ }
1647
+ if (typeof cwd === 'string') {
1648
+ let realCwd
1649
+ try {
1650
+ realCwd = await fsp.realpath(cwd)
1651
+ } catch {
1652
+ realCwd = undefined
1653
+ }
1654
+ if (realCwd !== undefined && (real === realCwd || insidePath(realCwd, real))) {
1655
+ return { error: '不能把隔离夹设在会话工作目录内' }
1656
+ }
1657
+ }
1658
+ return { root: real }
1659
+ }
1660
+
1661
+ /** The drive letters Windows exposes, skipping the ones that cannot be read. */
1662
+ async function listDriveRoots() {
1663
+ if (process.platform !== 'win32') return []
1664
+ const roots = []
1665
+ for (let code = 65; code <= 90; code += 1) {
1666
+ const drive = `${String.fromCharCode(code)}:\\`
1667
+ try {
1668
+ await fsp.access(drive)
1669
+ roots.push({ name: drive, path: drive })
1670
+ } catch {
1671
+ // absent or unreadable: not offered
1672
+ }
1673
+ }
1674
+ return roots
1675
+ }
1676
+
1677
+ /**
1678
+ * One directory listing for the folder picker. Directories only: the picker
1679
+ * chooses where a folder is created, so files would be noise.
1680
+ * @param target - absolute directory to list; the DSH home when omitted.
1681
+ */
1682
+ async function listDirectories(target) {
1683
+ const home = dshHome()
1684
+ const start = target === undefined || target === null || target === '' ? home : target
1685
+ if (typeof start !== 'string') throw new HttpError(400, 'invalid', 'path must be a string')
1686
+ if (!path.isAbsolute(start)) throw new HttpError(400, 'invalid', 'path must be absolute')
1687
+
1688
+ let real
1689
+ try {
1690
+ real = await fsp.realpath(start)
1691
+ } catch {
1692
+ throw new HttpError(400, 'invalid', `目录不存在:${start}`)
1693
+ }
1694
+ let entries
1695
+ try {
1696
+ entries = await fsp.readdir(real, { withFileTypes: true })
1697
+ } catch (error) {
1698
+ throw new HttpError(400, 'invalid', `无法读取目录:${String((error && error.message) || error)}`)
1699
+ }
1700
+
1701
+ const directories = []
1702
+ for (const entry of entries) {
1703
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
1704
+ const full = path.join(real, entry.name)
1705
+ try {
1706
+ // `stat` follows a link, so a shortcut to a folder is still offered.
1707
+ const info = await fsp.stat(full)
1708
+ if (!info.isDirectory()) continue
1709
+ } catch {
1710
+ continue
1711
+ }
1712
+ directories.push({ name: entry.name, path: full })
1713
+ }
1714
+ directories.sort((a, b) => a.name.localeCompare(b.name))
1715
+
1716
+ const parent = real === path.parse(real).root ? null : path.dirname(real)
1717
+ return {
1718
+ path: real,
1719
+ parent,
1720
+ entries: directories.slice(0, MAX_BROWSE_ENTRIES),
1721
+ truncated: directories.length > MAX_BROWSE_ENTRIES,
1722
+ // At a drive root, offer the other drives so Windows users are not stranded.
1723
+ roots: parent === null ? await listDriveRoots() : [],
1724
+ defaultRoot: home,
1725
+ }
1726
+ }
1727
+
1728
+ /**
1729
+ * Run one PowerShell invocation and resolve its trimmed stdout.
1730
+ *
1731
+ * The script is passed as a file, never on stdin: `-Command -` reads stdin with
1732
+ * the console code page, and a non-ASCII byte in the script (the Chinese dialog
1733
+ * description, for one) silently killed the whole run instead of erroring.
1734
+ */
1735
+ function runPowershell(args, timeoutMs) {
1736
+ return new Promise((resolve, reject) => {
1737
+ const child = spawn('powershell.exe', args, {
1738
+ windowsHide: true,
1739
+ })
1740
+ let out = ''
1741
+ let err = ''
1742
+ let settled = false
1743
+ const finish = (fn, value) => {
1744
+ if (settled) return
1745
+ settled = true
1746
+ clearTimeout(timer)
1747
+ fn(value)
1748
+ }
1749
+ const timer = setTimeout(() => {
1750
+ try { child.kill() } catch { /* already gone */ }
1751
+ finish(reject, new HttpError(504, 'timeout', '等待系统对话框超时'))
1752
+ }, timeoutMs)
1753
+
1754
+ child.stdout.on('data', (chunk) => { out += chunk.toString('utf8') })
1755
+ child.stderr.on('data', (chunk) => { err += chunk.toString('utf8') })
1756
+ child.on('error', (error) => {
1757
+ finish(reject, new HttpError(500, 'spawn', `无法启动系统对话框:${String((error && error.message) || error)}`))
1758
+ })
1759
+ child.on('close', (code) => {
1760
+ if (code !== 0) {
1761
+ finish(reject, new HttpError(500, 'shell', `系统对话框异常退出(${code}):${err.trim().slice(0, 300)}`))
1762
+ return
1763
+ }
1764
+ finish(resolve, out.trim())
1765
+ })
1766
+ })
1767
+ }
1768
+
1769
+ /**
1770
+ * Open a directory in the operating system's file manager. The child is detached
1771
+ * and unreferenced so the HTTP response returns at once and the window lives on
1772
+ * its own; `explorer.exe` reports a non-zero exit even when it succeeds, so its
1773
+ * status is deliberately ignored.
1774
+ */
1775
+ function revealDirectory(directory) {
1776
+ const opener = process.platform === 'win32'
1777
+ ? { program: 'explorer.exe', args: [directory] }
1778
+ : process.platform === 'darwin'
1779
+ ? { program: 'open', args: [directory] }
1780
+ : { program: 'xdg-open', args: [directory] }
1781
+ const child = spawn(opener.program, opener.args, { detached: true, stdio: 'ignore', windowsHide: false })
1782
+ // Without this listener a failed spawn (explorer missing, blocked by security
1783
+ // software) surfaces as an unhandled `error` event and takes the host down.
1784
+ child.on('error', () => {})
1785
+ child.unref()
1786
+ }
1787
+
1788
+ /**
1789
+ * Ask the host for a directory.
1790
+ *
1791
+ * DSH mounts `ctx.directoryPicker` (`@deepseek-ai/dsh-host-directory-picker-auto`),
1792
+ * whose capability names the interaction this deployment supports: a native
1793
+ * deployment opens one OS chooser, a browse deployment serves a listing the page
1794
+ * draws itself. Consumers are meant to switch on `capability().kind`.
1795
+ *
1796
+ * This plugin used to compile its own C# chooser and fall back to PowerShell. That
1797
+ * was a reimplementation of something the host already ships, it could not follow a
1798
+ * remote deployment, and it needed a compiler on the machine at first use.
1799
+ *
1800
+ * @returns `{ cancelled, path }` from a native chooser, else `{ browse: true }` or
1801
+ * `{ unsupported: true }` so the page falls back to its own picker.
1802
+ */
1803
+ async function pickFolder(ctx) {
1804
+ const picker = ctx !== null && ctx !== undefined && typeof ctx.get === 'function'
1805
+ ? ctx.get('directoryPicker')
1806
+ : undefined
1807
+ if (picker === null || picker === undefined || typeof picker.capability !== 'function') {
1808
+ return { unsupported: true }
1809
+ }
1810
+ let capability
1811
+ try {
1812
+ capability = picker.capability()
1813
+ } catch {
1814
+ return { unsupported: true }
1815
+ }
1816
+ if (capability === null || capability === undefined) return { unsupported: true }
1817
+ if (capability.kind !== 'native' || typeof capability.pick !== 'function') return { browse: true }
1818
+ // `pick(signal)` is mandatory: the host implementation begins with
1819
+ // `if (signal.aborted) throw …`, so calling it bare throws a TypeError that
1820
+ // reads like an unrelated failure ("… reading 'aborted'"). The timeout matches
1821
+ // the one the previous PowerShell dialog used: a dialog nobody answers must not
1822
+ // hold the request forever.
1823
+ const controller = new AbortController()
1824
+ const timer = setTimeout(() => controller.abort(), PICK_TIMEOUT_MS)
1825
+ let picked
1826
+ try {
1827
+ picked = await capability.pick(controller.signal)
1828
+ } finally {
1829
+ clearTimeout(timer)
1830
+ }
1831
+ const chosen = typeof picked === 'string' && picked !== '' ? picked : null
1832
+ if (chosen === null) return { cancelled: true, path: null }
1833
+ const resolved = path.resolve(chosen)
1834
+ let info
1835
+ try {
1836
+ info = await fsp.stat(resolved)
1837
+ } catch {
1838
+ throw new HttpError(400, 'invalid', '选中的目录已不存在')
1839
+ }
1840
+ if (!info.isDirectory()) throw new HttpError(400, 'invalid', '选中的不是目录')
1841
+ return { cancelled: false, path: resolved }
1842
+ }
1843
+
1844
+
1845
+ // --- http --------------------------------------------------------------------
1846
+
1847
+ function isLoopbackAddress(address) {
1848
+ if (typeof address !== 'string' || address.length === 0) return false
1849
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1' || address.startsWith('127.')
1850
+ }
1851
+
1852
+ function isLocalHostHeader(host) {
1853
+ if (typeof host !== 'string' || host.length === 0) return false
1854
+ const name = host.split(':')[0].replace(/^\[|\]$/g, '').toLowerCase()
1855
+ return name === 'localhost' || name === '127.0.0.1' || name === '::1'
1856
+ }
1857
+
1858
+ function sendJson(res, status, body) {
1859
+ const payload = JSON.stringify(body)
1860
+ res.writeHead(status, {
1861
+ 'content-type': 'application/json; charset=utf-8',
1862
+ 'content-length': Buffer.byteLength(payload),
1863
+ })
1864
+ res.end(payload)
1865
+ }
1866
+
1867
+ function readBody(req) {
1868
+ return new Promise((resolve, reject) => {
1869
+ let data = ''
1870
+ req.on('data', (chunk) => {
1871
+ data += chunk
1872
+ if (data.length > 1e6) req.destroy()
1873
+ })
1874
+ req.on('end', () => resolve(data))
1875
+ req.on('error', reject)
1876
+ req.on('aborted', () => reject(new Error('aborted')))
1877
+ })
1878
+ }
1879
+
1880
+ // Destructive local endpoint: loopback socket, loopback Host header, and a
1881
+ // same-origin check when the browser sends Origin. Tunneled or LAN clients
1882
+ // get 403 before any session data is touched.
1883
+ function guard(req, res) {
1884
+ if (!isLoopbackAddress(req.socket && req.socket.remoteAddress)) {
1885
+ sendJson(res, 403, { ok: false, code: 'forbidden', error: 'loopback only' })
1886
+ return false
1887
+ }
1888
+ const host = req.headers.host
1889
+ if (!isLocalHostHeader(host)) {
1890
+ sendJson(res, 403, { ok: false, code: 'forbidden', error: 'unexpected host' })
1891
+ return false
1892
+ }
1893
+ const origin = req.headers.origin
1894
+ if (typeof origin === 'string' && origin.length > 0) {
1895
+ let originHost = null
1896
+ try {
1897
+ originHost = new URL(origin).host
1898
+ } catch {
1899
+ originHost = null
1900
+ }
1901
+ if (originHost !== host) {
1902
+ sendJson(res, 403, { ok: false, code: 'forbidden', error: 'cross-origin request' })
1903
+ return false
1904
+ }
1905
+ }
1906
+ return true
1907
+ }
1908
+
1909
+ // --- plugin ------------------------------------------------------------------
1910
+
1911
+ export function apply(ctx) {
1912
+ warmCompiledHelpers()
1913
+
1914
+ const registerRoutes = (webServer, fiber) => {
1915
+ // Read-only scan: the dialog shows what a delete would move, before it does.
1916
+ fiber.effect(() => webServer.register({
1917
+ kind: 'exact',
1918
+ path: `${ROUTE_PREFIX}/artifacts`,
1919
+ handler: async (req, res) => {
1920
+ if (!guard(req, res)) return
1921
+ if (req.method !== 'POST') {
1922
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1923
+ return
1924
+ }
1925
+ let body = {}
1926
+ try {
1927
+ const raw = await readBody(req)
1928
+ if (raw) body = JSON.parse(raw)
1929
+ } catch {
1930
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
1931
+ return
1932
+ }
1933
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
1934
+ if (!sessionId) {
1935
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'sessionId required' })
1936
+ return
1937
+ }
1938
+ try {
1939
+ if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
1940
+ const plan = await planArtifacts(ctx, sessionId, undefined, { skipGit: body.skipGit === true })
1941
+ // A bad save path is reported alongside the plan rather than replacing
1942
+ // it: the dialog can still show the files while saying where they cannot go.
1943
+ const rootInfo = await resolveQuarantineRoot(body.root, plan.cwd)
1944
+ sendJson(res, 200, {
1945
+ ok: true,
1946
+ sessionId,
1947
+ ...plan,
1948
+ defaultRoot: dshHome(),
1949
+ quarantineRoot: rootInfo.error === undefined ? rootInfo.root : null,
1950
+ rootError: rootInfo.error === undefined ? null : rootInfo.error,
1951
+ })
1952
+ } catch (error) {
1953
+ const status = error instanceof HttpError ? error.status : 500
1954
+ const code = error instanceof HttpError ? error.code : 'internal'
1955
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1956
+ }
1957
+ },
1958
+ }))
1959
+
1960
+ // Delete ONE produced file from the dialog. The path must be one the scan
1961
+ // listed, so this cannot become a general-purpose delete primitive.
1962
+ fiber.effect(() => webServer.register({
1963
+ kind: 'exact',
1964
+ path: `${ROUTE_PREFIX}/delete-file`,
1965
+ handler: async (req, res) => {
1966
+ if (!guard(req, res)) return
1967
+ if (req.method !== 'POST') {
1968
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
1969
+ return
1970
+ }
1971
+ let body = {}
1972
+ try {
1973
+ const raw = await readBody(req)
1974
+ if (raw) body = JSON.parse(raw)
1975
+ } catch {
1976
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
1977
+ return
1978
+ }
1979
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
1980
+ const target = typeof body.path === 'string' ? body.path.trim() : ''
1981
+ try {
1982
+ if (sessionId === '') throw new HttpError(400, 'invalid', 'sessionId required')
1983
+ if (target === '') throw new HttpError(400, 'invalid', 'path required')
1984
+ if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
1985
+ const plan = await planArtifacts(ctx, sessionId, undefined, {})
1986
+ const resolved = assertListedPath(plan, target)
1987
+ const result = await removeOneFile(resolved, body.recycle === true)
1988
+ sendJson(res, 200, { ok: true, ...result })
1989
+ } catch (error) {
1990
+ const status = error instanceof HttpError ? error.status : 500
1991
+ const code = error instanceof HttpError ? error.code : 'internal'
1992
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
1993
+ }
1994
+ },
1995
+ }))
1996
+
1997
+ // The real Windows folder dialog, raised on the user's behalf. Browsers cannot
1998
+ // hand a page a filesystem path, but this process is local, so it can.
1999
+ fiber.effect(() => webServer.register({
2000
+ kind: 'exact',
2001
+ path: `${ROUTE_PREFIX}/pick`,
2002
+ handler: async (req, res) => {
2003
+ if (!guard(req, res)) return
2004
+ if (req.method !== 'POST') {
2005
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2006
+ return
2007
+ }
2008
+ try {
2009
+ const picked = await pickFolder(ctx)
2010
+ if (picked.unsupported === true) {
2011
+ sendJson(res, 200, { ok: false, code: 'unsupported', error: '宿主没有 directoryPicker 服务' })
2012
+ return
2013
+ }
2014
+ if (picked.browse === true) {
2015
+ sendJson(res, 200, { ok: false, code: 'browse', error: '浏览式宿主,请用页面内的选择器' })
2016
+ return
2017
+ }
2018
+ sendJson(res, 200, { ok: true, ...picked })
2019
+ } catch (error) {
2020
+ const status = error instanceof HttpError ? error.status : 500
2021
+ const code = error instanceof HttpError ? error.code : 'internal'
2022
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2023
+ }
2024
+ },
2025
+ }))
2026
+
2027
+ // Open a folder in the OS file manager. The path is validated as an existing
2028
+ // directory first: this hands a string to Explorer, so it must never be able
2029
+ // to carry anything but a directory.
2030
+ fiber.effect(() => webServer.register({
2031
+ kind: 'exact',
2032
+ path: `${ROUTE_PREFIX}/reveal`,
2033
+ handler: async (req, res) => {
2034
+ if (!guard(req, res)) return
2035
+ if (req.method !== 'POST') {
2036
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2037
+ return
2038
+ }
2039
+ let body = {}
2040
+ try {
2041
+ const raw = await readBody(req)
2042
+ if (raw) body = JSON.parse(raw)
2043
+ } catch {
2044
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2045
+ return
2046
+ }
2047
+ try {
2048
+ const target = typeof body.path === 'string' ? body.path.trim() : ''
2049
+ if (target === '') throw new HttpError(400, 'invalid', 'path required')
2050
+ const resolved = path.resolve(target)
2051
+ let info
2052
+ try {
2053
+ info = await fsp.stat(resolved)
2054
+ } catch {
2055
+ throw new HttpError(400, 'invalid', '目录不存在')
2056
+ }
2057
+ if (!info.isDirectory()) throw new HttpError(400, 'invalid', '不是目录')
2058
+ revealDirectory(resolved)
2059
+ sendJson(res, 200, { ok: true, path: resolved })
2060
+ } catch (error) {
2061
+ const status = error instanceof HttpError ? error.status : 500
2062
+ const code = error instanceof HttpError ? error.code : 'internal'
2063
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2064
+ }
2065
+ },
2066
+ }))
2067
+
2068
+ // Folder picker for the quarantine save path: directories only, never file
2069
+ // contents, and the same loopback guard as every other route here.
2070
+ fiber.effect(() => webServer.register({
2071
+ kind: 'exact',
2072
+ path: `${ROUTE_PREFIX}/browse`,
2073
+ handler: async (req, res) => {
2074
+ if (!guard(req, res)) return
2075
+ if (req.method !== 'POST') {
2076
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2077
+ return
2078
+ }
2079
+ let body = {}
2080
+ try {
2081
+ const raw = await readBody(req)
2082
+ if (raw) body = JSON.parse(raw)
2083
+ } catch {
2084
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2085
+ return
2086
+ }
2087
+ try {
2088
+ const listing = await listDirectories(body.path)
2089
+ sendJson(res, 200, { ok: true, ...listing })
2090
+ } catch (error) {
2091
+ const status = error instanceof HttpError ? error.status : 500
2092
+ const code = error instanceof HttpError ? error.code : 'internal'
2093
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2094
+ }
2095
+ },
2096
+ }))
2097
+
2098
+ // The subagent sessions behind one conversation. A subagent is a session of
2099
+ // its own, linked only by `parentSession`, so the dialog needs this list
2100
+ // before it can offer anything to tick.
2101
+ fiber.effect(() => webServer.register({
2102
+ kind: 'exact',
2103
+ path: `${ROUTE_PREFIX}/children`,
2104
+ handler: async (req, res) => {
2105
+ if (!guard(req, res)) return
2106
+ if (req.method !== 'POST') {
2107
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2108
+ return
2109
+ }
2110
+ let body = {}
2111
+ try {
2112
+ const raw = await readBody(req)
2113
+ if (raw) body = JSON.parse(raw)
2114
+ } catch {
2115
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2116
+ return
2117
+ }
2118
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
2119
+ if (!SESSION_ID_RE.test(sessionId)) {
2120
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'invalid session id' })
2121
+ return
2122
+ }
2123
+ try {
2124
+ const headers = await listSessionHeaders(ctx)
2125
+ sendJson(res, 200, { ok: true, children: describeChildren(headers, sessionId) })
2126
+ } catch (error) {
2127
+ const status = error instanceof HttpError ? error.status : 500
2128
+ const code = error instanceof HttpError ? error.code : 'internal'
2129
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2130
+ }
2131
+ },
2132
+ }))
2133
+ fiber.effect(() => webServer.register({
2134
+ kind: 'exact',
2135
+ path: `${ROUTE_PREFIX}/delete`,
2136
+ handler: async (req, res) => {
2137
+ if (!guard(req, res)) return
2138
+ if (req.method !== 'POST') {
2139
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2140
+ return
2141
+ }
2142
+ let body = {}
2143
+ try {
2144
+ const raw = await readBody(req)
2145
+ if (raw) body = JSON.parse(raw)
2146
+ } catch {
2147
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2148
+ return
2149
+ }
2150
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId.trim() : ''
2151
+ if (!sessionId) {
2152
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'sessionId required' })
2153
+ return
2154
+ }
2155
+ try {
2156
+ // Validate before touching anything: the quarantine runs first, so an
2157
+ // unchecked id would reach the filesystem ahead of deleteSession's own
2158
+ // guard. `/artifacts` already validates at the same point.
2159
+ if (!SESSION_ID_RE.test(sessionId)) throw new HttpError(400, 'invalid', 'invalid session id')
2160
+ // Quarantine first: the session log is still there to derive the plan
2161
+ // from, and a partial move leaves the conversation intact to retry.
2162
+ const wantsQuarantine = typeof body.quarantine === 'object' && body.quarantine !== null
2163
+ // The plan handed to the move must honour the same `skipGit` the dialog
2164
+ // listed, or a file the listing refused to show would move anyway.
2165
+ const plan = wantsQuarantine
2166
+ ? await planArtifacts(ctx, sessionId, undefined, { skipGit: body.quarantine.skipGit === true })
2167
+ : null
2168
+ const quarantine = await runQuarantine(ctx, sessionId, body.quarantine, plan)
2169
+ const result = await deleteSession(ctx, sessionId, {
2170
+ recycle: body.recycle !== false,
2171
+ childSessionIds: Array.isArray(body.childSessionIds) ? body.childSessionIds : [],
2172
+ })
2173
+ sendJson(res, 200, quarantine === null ? { ok: true, ...result } : { ok: true, ...result, quarantine })
2174
+ } catch (error) {
2175
+ const status = error instanceof HttpError ? error.status : 500
2176
+ const code = error instanceof HttpError ? error.code : 'internal'
2177
+ sendJson(res, status, { ok: false, code, error: String((error && error.message) || error) })
2178
+ }
2179
+ },
2180
+ }))
2181
+
2182
+ fiber.effect(() => webServer.register({
2183
+ kind: 'exact',
2184
+ path: `${ROUTE_PREFIX}/delete-many`,
2185
+ handler: async (req, res) => {
2186
+ if (!guard(req, res)) return
2187
+ if (req.method !== 'POST') {
2188
+ sendJson(res, 405, { ok: false, code: 'method', error: 'POST only' })
2189
+ return
2190
+ }
2191
+ let body = {}
2192
+ try {
2193
+ const raw = await readBody(req)
2194
+ if (raw) body = JSON.parse(raw)
2195
+ } catch {
2196
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'malformed JSON body' })
2197
+ return
2198
+ }
2199
+ const sessionIds = Array.isArray(body.sessionIds)
2200
+ ? [...new Set(body.sessionIds.filter((id) => typeof id === 'string' && id.trim()).map((id) => id.trim()))]
2201
+ : []
2202
+ if (sessionIds.length === 0) {
2203
+ sendJson(res, 400, { ok: false, code: 'invalid', error: 'sessionIds required' })
2204
+ return
2205
+ }
2206
+ if (sessionIds.length > MAX_BATCH) {
2207
+ sendJson(res, 400, { ok: false, code: 'invalid', error: `too many sessions (max ${MAX_BATCH})` })
2208
+ return
2209
+ }
2210
+ // Bounded-concurrency batch: every item runs the same guarded pipeline
2211
+ // (lease retry, directory sweep, workspace accounting); independent
2212
+ // sessions run in parallel and the workspace accounting mutation is
2213
+ // serialized inside deleteSession, so a batch can never interleave two
2214
+ // deletions of the same storage.
2215
+ const results = await deleteSessions(ctx, sessionIds, {
2216
+ recycle: body.recycle !== false,
2217
+ childSessionIds: Array.isArray(body.childSessionIds) ? body.childSessionIds : [],
2218
+ })
2219
+ const deleted = results.filter((item) => item.ok).length
2220
+ sendJson(res, 200, { ok: true, results, deleted, failed: results.length - deleted })
2221
+ },
2222
+ }))
2223
+ }
2224
+
2225
+ const webServer = ctx.get('webServer')
2226
+ if (webServer) {
2227
+ registerRoutes(webServer, ctx)
2228
+ } else {
2229
+ // A terminal-only profile never provides a web surface; register once one
2230
+ // appears instead of waiting on a service that will never arrive.
2231
+ ctx.inject(['webServer'], (sub) => registerRoutes(sub.webServer, sub))
2232
+ }
2233
+ }
2234
+
2235
+ // Re-exported for the offline test suite, which drives the artifact plan and the
2236
+ // quarantine against a scratch tree and a stubbed persistence service. Nothing
2237
+ // else in the host reads this face.
2238
+ export const internals = {
2239
+ pickFolder,
2240
+ artifactCandidates,
2241
+ assertListedPath,
2242
+ removeOneFile,
2243
+ claimQuarantineDirectory,
2244
+ classifyPaths,
2245
+ collectSessionPaths,
2246
+ MAX_SCANNED,
2247
+ findSessionCaches,
2248
+ freeDestination,
2249
+ identityKey,
2250
+ insidePath,
2251
+ listDirectories,
2252
+ moveToSessionTrash,
2253
+ planArtifacts,
2254
+ quarantineFiles,
2255
+ resolveQuarantineRoot,
2256
+ removeForever,
2257
+ deleteSession,
2258
+ deleteSessions,
2259
+ busyBackoff,
2260
+ BUSY_RETRY_ATTEMPTS,
2261
+ retirePaths,
2262
+ retireTargets,
2263
+ listSessionHeaders,
2264
+ collectOrphans,
2265
+ collectDescendants,
2266
+ bareSessionId,
2267
+ describeChildren,
2268
+ selectChildDeletes,
2269
+ runQuarantine,
2270
+ sendToRecycleBin,
2271
+ toolTarget,
2272
+ trashCommandFor,
2273
+ warmCompiledHelpers,
2274
+ }