@xiangyixie/dsh-superagent 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1119 @@
1
+ /**
2
+ * Local workspace panel for dsh-superagent.
3
+ *
4
+ * The panel is an IDE-shaped view over one directory on the machine that runs
5
+ * the host: a file tree, a plain-text editor, a diff preview before saving, and
6
+ * the list of files an earlier run touched. It deliberately does not ask the
7
+ * host for an API — the plugin owns the filesystem access itself.
8
+ *
9
+ * Safety properties, in order of importance:
10
+ *
11
+ * - Off unless `workbenchPort` is configured.
12
+ * - Bound to 127.0.0.1, never a routable interface.
13
+ * - Every request needs `Authorization: Bearer <token>`. The token is random
14
+ * per process and written to `<stateDir>/workbench.json` with mode 0600.
15
+ * - Every path is resolved, then realpath-resolved, then checked against the
16
+ * configured workspace root. A symlink that points outside is refused, and
17
+ * the reason is sent back instead of an empty 404.
18
+ * - The plugin state directory is always refused, so the panel cannot read the
19
+ * control-plane token that lives next to its own.
20
+ * - The `Host` header must name the loopback address, which blocks DNS
21
+ * rebinding; no CORS headers are sent.
22
+ * - Binary files and files above the edit limit are readable only as metadata.
23
+ * - Saving requires the hash and mtime the editor read, so a file changed by
24
+ * another process is never overwritten silently.
25
+ *
26
+ * @module dsh-superagent/workbench
27
+ */
28
+ import { execFile } from 'node:child_process'
29
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'
30
+ import fsp from 'node:fs/promises'
31
+ import { createServer } from 'node:http'
32
+ import path from 'node:path'
33
+ import { promisify } from 'node:util'
34
+ import { ACTIVE_STATUSES, TERMINAL_STATUSES } from './store.js'
35
+
36
+ const execFileAsync = promisify(execFile)
37
+
38
+ /** Bodies are editor text plus a little JSON; nothing here uploads a file. */
39
+ const BODY_LIMIT = 2 * 1024 * 1024
40
+ /** Above this a file is shown as a read-only size hint instead of an editor. */
41
+ export const MAX_EDIT_BYTES = 512 * 1024
42
+ /** One directory listing is capped so a generated folder cannot pin the host. */
43
+ const TREE_LIMIT = 2000
44
+ const SNAPSHOT_LIMIT = 4000
45
+ const REQUEST_TIMEOUT_MS = 30_000
46
+ const DISCOVERY_FILE = 'workbench.json'
47
+ const ROUTE_HINT = 'GET / serves the panel; the JSON API is under /api.'
48
+ /** Directories a change snapshot never walks into. */
49
+ const SNAPSHOT_SKIP = new Set(['.git', '.hg', '.svn', 'node_modules'])
50
+
51
+ /** Error shape used by the routing layer to choose a status code. */
52
+ class WorkbenchError extends Error {
53
+ constructor(status, message, { id = 'bad-request', hint } = {}) {
54
+ super(message)
55
+ this.status = status
56
+ this.id = id
57
+ this.hint = hint
58
+ }
59
+ }
60
+
61
+ function sha256(buffer) {
62
+ return createHash('sha256').update(buffer).digest('hex')
63
+ }
64
+
65
+ function sameToken(given, expected) {
66
+ const a = Buffer.from(given)
67
+ const b = Buffer.from(expected)
68
+ return a.length === b.length && timingSafeEqual(a, b)
69
+ }
70
+
71
+ /** A NUL byte in the head of a file is the cheap, stable binary signal. */
72
+ export function looksBinary(buffer) {
73
+ const head = buffer.subarray(0, 8000)
74
+ return head.includes(0)
75
+ }
76
+
77
+ /** Send JSON with the headers every response in this module shares. */
78
+ function send(res, status, payload, extra = {}) {
79
+ if (res.headersSent) return
80
+ const body = `${JSON.stringify(payload)}\n`
81
+ res.writeHead(status, {
82
+ 'content-type': 'application/json; charset=utf-8',
83
+ 'content-length': Buffer.byteLength(body),
84
+ 'cache-control': 'no-store',
85
+ 'x-content-type-options': 'nosniff',
86
+ ...extra,
87
+ })
88
+ res.end(body)
89
+ }
90
+
91
+ function sendText(res, status, text, type = 'text/plain; charset=utf-8', extra = {}) {
92
+ if (res.headersSent) return
93
+ res.writeHead(status, {
94
+ 'content-type': type,
95
+ 'content-length': Buffer.byteLength(text),
96
+ 'cache-control': 'no-store',
97
+ 'x-content-type-options': 'nosniff',
98
+ ...extra,
99
+ })
100
+ res.end(text)
101
+ }
102
+
103
+ function errorPayload(error) {
104
+ if (error instanceof WorkbenchError) {
105
+ return {
106
+ ok: false,
107
+ error: { id: error.id, summary: error.message, hint: error.hint ?? null, detail: error.message },
108
+ }
109
+ }
110
+ const code = error?.code ? `${error.code}: ` : ''
111
+ return {
112
+ ok: false,
113
+ error: { id: 'internal', summary: `${code}${error?.message ?? String(error)}`, hint: null },
114
+ }
115
+ }
116
+
117
+ function statusFor(error) {
118
+ return error instanceof WorkbenchError ? error.status : 500
119
+ }
120
+
121
+ /** Read one request body as text, refusing anything above the cap. */
122
+ function readBody(req, limit = BODY_LIMIT) {
123
+ return new Promise((resolve, reject) => {
124
+ const chunks = []
125
+ let size = 0
126
+ let settled = false
127
+ const fail = error => {
128
+ if (settled) return
129
+ settled = true
130
+ reject(error)
131
+ }
132
+ req.on('data', chunk => {
133
+ if (settled) return
134
+ size += chunk.length
135
+ if (size > limit) {
136
+ fail(new WorkbenchError(413, `request body is larger than ${limit} bytes`, {
137
+ id: 'body-too-large',
138
+ hint: 'the editor sends text only; keep one save under the documented limit.',
139
+ }))
140
+ req.resume()
141
+ return
142
+ }
143
+ chunks.push(chunk)
144
+ })
145
+ req.on('end', () => {
146
+ if (settled) return
147
+ settled = true
148
+ resolve(Buffer.concat(chunks).toString('utf8'))
149
+ })
150
+ req.on('error', fail)
151
+ req.on('aborted', () => fail(new WorkbenchError(400, 'the client aborted the request', { id: 'aborted' })))
152
+ })
153
+ }
154
+
155
+ async function readJson(req) {
156
+ const text = (await readBody(req)).trim()
157
+ if (!text) return {}
158
+ let parsed
159
+ try {
160
+ parsed = JSON.parse(text)
161
+ } catch (error) {
162
+ throw new WorkbenchError(400, `request body is not JSON: ${error?.message ?? error}`, {
163
+ id: 'bad-json',
164
+ hint: 'send a JSON object.',
165
+ })
166
+ }
167
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
168
+ throw new WorkbenchError(400, 'request body must be a JSON object', { id: 'bad-json' })
169
+ }
170
+ return parsed
171
+ }
172
+
173
+ /**
174
+ * Split text into diff lines, remembering whether the final newline exists.
175
+ * @param {string} text - input.
176
+ * @returns {{ lines: string[], finalNewline: boolean }} lines without the
177
+ * trailing empty element.
178
+ */
179
+ function splitLines(text) {
180
+ if (text === '') return { lines: [], finalNewline: false }
181
+ const finalNewline = text.endsWith('\n')
182
+ const lines = text.split('\n')
183
+ if (finalNewline) lines.pop()
184
+ return { lines, finalNewline }
185
+ }
186
+
187
+ /**
188
+ * Myers difference over two line arrays. Bounded by the number of lines, which
189
+ * is already bounded by the edit size cap, so no O(n*m) table is allocated.
190
+ *
191
+ * @param {string[]} before - old lines.
192
+ * @param {string[]} after - new lines.
193
+ * @returns {{ type: ' ' | '-' | '+', line: string }[]} edit script.
194
+ */
195
+ function diffOps(before, after) {
196
+ const n = before.length
197
+ const m = after.length
198
+ if (n === 0) return after.map(line => ({ type: '+', line }))
199
+ if (m === 0) return before.map(line => ({ type: '-', line }))
200
+ const max = n + m
201
+ const trace = []
202
+ const v = new Map()
203
+ v.set(1, 0)
204
+ let found = -1
205
+ for (let d = 0; d <= max && found < 0; d++) {
206
+ trace.push(new Map(v))
207
+ for (let k = -d; k <= d; k += 2) {
208
+ const down = k === -d || (k !== d && (v.get(k - 1) ?? -Infinity) < (v.get(k + 1) ?? -Infinity))
209
+ let x = down ? (v.get(k + 1) ?? 0) : (v.get(k - 1) ?? 0) + 1
210
+ let y = x - k
211
+ while (x < n && y < m && before[x] === after[y]) {
212
+ x++
213
+ y++
214
+ }
215
+ v.set(k, x)
216
+ if (x >= n && y >= m) {
217
+ found = d
218
+ break
219
+ }
220
+ }
221
+ }
222
+
223
+ const ops = []
224
+ let x = n
225
+ let y = m
226
+ for (let d = found; d > 0; d--) {
227
+ const previous = trace[d]
228
+ const k = x - y
229
+ const down = k === -d || (k !== d && (previous.get(k - 1) ?? -Infinity) < (previous.get(k + 1) ?? -Infinity))
230
+ const prevK = down ? k + 1 : k - 1
231
+ const prevX = previous.get(prevK) ?? 0
232
+ const prevY = prevX - prevK
233
+ while (x > prevX && y > prevY) {
234
+ ops.push({ type: ' ', line: before[x - 1] })
235
+ x--
236
+ y--
237
+ }
238
+ if (x === prevX) {
239
+ ops.push({ type: '+', line: after[y - 1] })
240
+ y--
241
+ } else {
242
+ ops.push({ type: '-', line: before[x - 1] })
243
+ x--
244
+ }
245
+ }
246
+ while (x > 0 && y > 0) {
247
+ ops.push({ type: ' ', line: before[x - 1] })
248
+ x--
249
+ y--
250
+ }
251
+ while (x > 0) ops.push({ type: '-', line: before[--x] })
252
+ while (y > 0) ops.push({ type: '+', line: after[--y] })
253
+ ops.reverse()
254
+ return ops
255
+ }
256
+
257
+ /**
258
+ * Render a unified diff between two strings.
259
+ *
260
+ * A small hand-written implementation keeps the package dependency-free; it is
261
+ * used both for the save preview and for a run's changed files.
262
+ *
263
+ * @param {string} beforeText - original content.
264
+ * @param {string} afterText - proposed content.
265
+ * @param {{ path?: string, context?: number }} [options] - header path and context lines.
266
+ * @returns {string} unified diff, or an empty string when nothing changed.
267
+ */
268
+ export function createUnifiedDiff(beforeText, afterText, options = {}) {
269
+ const before = splitLines(beforeText)
270
+ const after = splitLines(afterText)
271
+ const ops = diffOps(before.lines, after.lines)
272
+ let oldNo = 1
273
+ let newNo = 1
274
+ for (const op of ops) {
275
+ op.oldNo = op.type === '+' ? null : oldNo++
276
+ op.newNo = op.type === '-' ? null : newNo++
277
+ }
278
+ const changes = ops
279
+ .map((op, index) => (op.type === ' ' ? -1 : index))
280
+ .filter(index => index >= 0)
281
+ if (changes.length === 0) return ''
282
+
283
+ const context = Math.max(0, Math.trunc(options.context ?? 3))
284
+ const runs = []
285
+ for (const index of changes) {
286
+ const last = runs.at(-1)
287
+ if (last && index - last.end <= context * 2 + 1) last.end = index
288
+ else runs.push({ start: index, end: index })
289
+ }
290
+
291
+ const header = [
292
+ `--- a/${options.path ?? 'file'}`,
293
+ `+++ b/${options.path ?? 'file'}`,
294
+ ]
295
+ let added = 0
296
+ let removed = 0
297
+ for (const op of ops) {
298
+ if (op.type === '+') added++
299
+ if (op.type === '-') removed++
300
+ }
301
+ header.push(`# ${added} added, ${removed} removed`)
302
+
303
+ const body = []
304
+ for (const run of runs) {
305
+ const from = Math.max(0, run.start - context)
306
+ const to = Math.min(ops.length - 1, run.end + context)
307
+ const hunk = ops.slice(from, to + 1)
308
+ const oldCount = hunk.filter(op => op.type !== '+').length
309
+ const newCount = hunk.filter(op => op.type !== '-').length
310
+ const firstOld = hunk.find(op => op.oldNo !== null)?.oldNo
311
+ const firstNew = hunk.find(op => op.newNo !== null)?.newNo
312
+ const oldStart = oldCount > 0 ? firstOld : (hunk[0].oldNo ?? 1) - 1
313
+ const newStart = newCount > 0 ? firstNew : (hunk[0].newNo ?? 1) - 1
314
+ body.push(`@@ -${Math.max(0, oldStart)},${oldCount} +${Math.max(0, newStart)},${newCount} @@`)
315
+ for (const op of hunk) body.push(`${op.type}${op.line}`)
316
+ }
317
+ return `${[...header, ...body].join('\n')}\n`
318
+ }
319
+
320
+ /** Count a diff's added and removed lines, for a compact preview label. */
321
+ export function diffStats(diff) {
322
+ let added = 0
323
+ let removed = 0
324
+ for (const line of String(diff).split('\n')) {
325
+ if (line.startsWith('+') && !line.startsWith('+++')) added++
326
+ if (line.startsWith('-') && !line.startsWith('---')) removed++
327
+ }
328
+ return { added, removed }
329
+ }
330
+
331
+ /** Compare two absolute paths case-insensitively on Windows. */
332
+ function isInside(parent, child) {
333
+ const base = process.platform === 'win32' ? parent.toLowerCase() : parent
334
+ const target = process.platform === 'win32' ? child.toLowerCase() : child
335
+ return target === base || target.startsWith(base.endsWith(path.sep) ? base : `${base}${path.sep}`)
336
+ }
337
+
338
+ /** Walk one workspace without reading file contents, for change detection. */
339
+ async function snapshotTree(root, { stateRoot, maxFiles = SNAPSHOT_LIMIT } = {}) {
340
+ const files = new Map()
341
+ const stack = ['']
342
+ let truncated = false
343
+ while (stack.length > 0) {
344
+ const relative = stack.pop()
345
+ const absolute = relative ? path.join(root, relative) : root
346
+ let entries
347
+ try {
348
+ entries = await fsp.readdir(absolute, { withFileTypes: true })
349
+ } catch {
350
+ continue
351
+ }
352
+ for (const entry of entries) {
353
+ if (files.size >= maxFiles) {
354
+ truncated = true
355
+ break
356
+ }
357
+ if (SNAPSHOT_SKIP.has(entry.name)) continue
358
+ const childAbs = path.join(absolute, entry.name)
359
+ if (stateRoot && isInside(stateRoot, childAbs)) continue
360
+ const childRel = relative ? `${relative}/${entry.name}` : entry.name
361
+ if (entry.isDirectory()) {
362
+ stack.push(childRel)
363
+ continue
364
+ }
365
+ if (!entry.isFile()) continue
366
+ try {
367
+ const stat = await fsp.stat(childAbs)
368
+ files.set(childRel, { size: stat.size, mtimeMs: stat.mtimeMs })
369
+ } catch {
370
+ // A file removed mid-walk is simply not part of this snapshot.
371
+ }
372
+ }
373
+ }
374
+ return { files, truncated }
375
+ }
376
+
377
+ /** Compare two snapshots into the list persisted on the run record. */
378
+ function changedFiles(before, after) {
379
+ const paths = new Set([...before.files.keys(), ...after.files.keys()])
380
+ const changes = []
381
+ for (const file of paths) {
382
+ const old = before.files.get(file)
383
+ const now = after.files.get(file)
384
+ if (!old && now) changes.push({ path: file, change: 'added', beforeBytes: 0, afterBytes: now.size })
385
+ else if (old && !now) changes.push({ path: file, change: 'deleted', beforeBytes: old.size, afterBytes: 0 })
386
+ else if (old && now && (old.size !== now.size || old.mtimeMs !== now.mtimeMs)) {
387
+ changes.push({ path: file, change: 'modified', beforeBytes: old.size, afterBytes: now.size })
388
+ }
389
+ }
390
+ changes.sort((a, b) => a.path.localeCompare(b.path))
391
+ return changes
392
+ }
393
+
394
+ /**
395
+ * Record which workspace files changed while a run was active.
396
+ *
397
+ * The orchestrator already persists one JSON record per run; this tracker wraps
398
+ * the store's `write` so the record itself carries `changes`, which is exactly
399
+ * what the panel reads later. The orchestrator file stays untouched and a run
400
+ * started while the panel is off simply has no `changes` field.
401
+ *
402
+ * @param {object} options - dependencies.
403
+ * @param {object} options.store - store returned by `createStore`.
404
+ * @param {string} options.root - absolute workspace root.
405
+ * @param {string} options.stateRoot - plugin state directory, excluded from snapshots.
406
+ * @param {(message: string) => void} [options.warn] - diagnostics sink.
407
+ * @returns {{ store: object }} the wrapped store.
408
+ */
409
+ export function createRunChangeTracker({ store, root, stateRoot, warn = () => {} }) {
410
+ const snapshots = new Map()
411
+ let queue = Promise.resolve()
412
+
413
+ async function track(run) {
414
+ if (!run || typeof run.id !== 'string') return
415
+ if (!snapshots.has(run.id) && ACTIVE_STATUSES.has(run.status)) {
416
+ snapshots.set(run.id, await snapshotTree(root, { stateRoot }))
417
+ return
418
+ }
419
+ if (TERMINAL_STATUSES.has(run.status) && !run.changes) {
420
+ const before = snapshots.get(run.id)
421
+ snapshots.delete(run.id)
422
+ if (!before) {
423
+ run.changes = {
424
+ root,
425
+ recordedAt: new Date().toISOString(),
426
+ files: [],
427
+ incomplete: true,
428
+ note: 'no snapshot was taken before this run started (it predates the workbench or resumed in another process), '
429
+ + 'so changed files cannot be attributed',
430
+ }
431
+ return
432
+ }
433
+ const after = await snapshotTree(root, { stateRoot })
434
+ run.changes = {
435
+ root,
436
+ recordedAt: new Date().toISOString(),
437
+ files: changedFiles(before, after),
438
+ truncated: before.truncated || after.truncated,
439
+ }
440
+ }
441
+ }
442
+
443
+ const wrapped = {
444
+ ...store,
445
+ async write(run) {
446
+ try {
447
+ await track(run)
448
+ } catch (error) {
449
+ warn(`cannot record changed files for run ${run?.id ?? '?'}: ${error?.message ?? error}`)
450
+ }
451
+ return store.write(run)
452
+ },
453
+ }
454
+ // Keep snapshot walks from overlapping when several runs write together.
455
+ const sequential = wrapped.write
456
+ wrapped.write = async run => {
457
+ const next = queue.catch(() => {}).then(() => sequential(run))
458
+ queue = next
459
+ return next
460
+ }
461
+ return { store: wrapped }
462
+ }
463
+
464
+ /**
465
+ * Ask git for the working-tree diff of one path.
466
+ *
467
+ * `git diff HEAD` already normalizes line endings the same way the checkout
468
+ * did, so a CRLF working tree does not turn into a whole-file diff. It also
469
+ * covers staged, unstaged, and deleted tracked files; untracked files produce
470
+ * an empty patch and are handled by the caller.
471
+ *
472
+ * @param {string} root - repository root.
473
+ * @param {string} relative - path relative to the root.
474
+ * @returns {Promise<{ patch: string|null, available: boolean, reason: string|null }>}
475
+ */
476
+ async function gitPatch(root, relative) {
477
+ try {
478
+ const { stdout } = await execFileAsync('git', ['-C', root, 'diff', 'HEAD', '--no-color', '--', relative], {
479
+ maxBuffer: 10 * 1024 * 1024,
480
+ timeout: 5000,
481
+ windowsHide: true,
482
+ encoding: 'utf8',
483
+ })
484
+ return { patch: stdout, available: true, reason: null }
485
+ } catch (error) {
486
+ const detail = String(error?.stderr ?? error?.message ?? error).trim()
487
+ const missingRepo = /not a git repository|not recognized as an internal|ENOENT/i.test(detail)
488
+ return { patch: null, available: !missingRepo, reason: detail || 'git could not diff this path' }
489
+ }
490
+ }
491
+
492
+ /** Whether git tracks a path, used to explain an empty diff. */
493
+ async function gitTracks(root, relative) {
494
+ try {
495
+ await execFileAsync('git', ['-C', root, 'ls-files', '--error-unmatch', '--', relative], {
496
+ maxBuffer: 1024 * 1024,
497
+ timeout: 5000,
498
+ windowsHide: true,
499
+ encoding: 'utf8',
500
+ })
501
+ return true
502
+ } catch {
503
+ return false
504
+ }
505
+ }
506
+
507
+ /**
508
+ * Create the panel. Nothing is bound until `start()` is called.
509
+ *
510
+ * @param {object} options - dependencies.
511
+ * @param {number} options.port - 1–65535, or 0 for an ephemeral port.
512
+ * @param {string} options.root - absolute workspace root; everything outside is refused.
513
+ * @param {string} options.stateRoot - plugin state directory; always refused.
514
+ * @param {object} [options.store] - run store, used by the run views.
515
+ * @param {string} options.version - plugin version reported by `/api/health`.
516
+ * @param {(message: string) => void} [options.log] - diagnostics sink.
517
+ */
518
+ export function createWorkbench({ port, root, stateRoot, store, version, log = () => {} }) {
519
+ const token = randomBytes(32).toString('base64url')
520
+ const instanceId = randomBytes(6).toString('hex')
521
+ const discoveryPath = path.join(stateRoot, DISCOVERY_FILE)
522
+ const startedAt = new Date().toISOString()
523
+ let realRoot = null
524
+ let realStateRoot = null
525
+ let boundPort = null
526
+ let server = null
527
+ let html = null
528
+ let writeSeq = 0
529
+ let starting = null
530
+ let stopRequested = false
531
+ let closing = null
532
+
533
+ const url = () => `http://127.0.0.1:${boundPort}`
534
+ const allowedHosts = () => new Set([
535
+ `127.0.0.1:${boundPort}`,
536
+ `localhost:${boundPort}`,
537
+ `[::1]:${boundPort}`,
538
+ ])
539
+
540
+ function authorize(req, { allowQuery = false } = {}) {
541
+ if (!boundPort) {
542
+ throw new WorkbenchError(503, 'the workbench is not listening yet', { id: 'not-ready' })
543
+ }
544
+ const host = String(req.headers.host ?? '').toLowerCase()
545
+ if (!allowedHosts().has(host)) {
546
+ throw new WorkbenchError(403, `unexpected Host header "${host}"; the workbench answers only on 127.0.0.1 and localhost`, {
547
+ id: 'forbidden-host',
548
+ hint: `open ${boundPort ? url() : 'the URL in the discovery file'} directly.`,
549
+ })
550
+ }
551
+ const header = String(req.headers.authorization ?? '')
552
+ const match = /^Bearer\s+(\S+)$/i.exec(header)
553
+ let given = match?.[1] ?? ''
554
+ if (!given && allowQuery) {
555
+ const query = new URL(req.url ?? '/', 'http://127.0.0.1').searchParams.get('token')
556
+ if (query) given = query
557
+ }
558
+ if (!given || !sameToken(given, token)) {
559
+ throw new WorkbenchError(401, 'missing or wrong access token', {
560
+ id: 'unauthorized',
561
+ hint: `read the "token" field in ${discoveryPath}, then open "url?token=<token>" once. `
562
+ + 'The token is regenerated each time the host starts.',
563
+ })
564
+ }
565
+ }
566
+
567
+ /**
568
+ * Resolve a client path inside the workspace.
569
+ *
570
+ * Absolute paths, drive letters, traversal, and symlinks that leave the root
571
+ * all fail with a readable reason. The plugin state directory is refused even
572
+ * though it may sit inside the root.
573
+ */
574
+ async function resolvePath(input) {
575
+ const raw = typeof input === 'string' ? input : ''
576
+ if (raw.includes('\0')) {
577
+ throw new WorkbenchError(400, 'the path contains a NUL byte', { id: 'bad-path' })
578
+ }
579
+ if (path.isAbsolute(raw) || /^[a-zA-Z]:/.test(raw) || raw.startsWith('\\\\')) {
580
+ throw new WorkbenchError(403, `"${raw}" is an absolute path; the workbench only serves paths inside its root`, {
581
+ id: 'outside-root',
582
+ hint: `use a path relative to ${root}.`,
583
+ })
584
+ }
585
+ const candidate = path.resolve(realRoot, raw || '.')
586
+ if (!isInside(realRoot, candidate)) {
587
+ throw new WorkbenchError(403, `"${raw}" resolves outside the workspace root ${root}`, {
588
+ id: 'outside-root',
589
+ hint: 'the panel cannot read or write anything above its configured root.',
590
+ })
591
+ }
592
+ let real
593
+ try {
594
+ real = await fsp.realpath(candidate)
595
+ } catch (error) {
596
+ if (error?.code === 'ENOENT') {
597
+ throw new WorkbenchError(404, `"${raw}" does not exist`, { id: 'not-found' })
598
+ }
599
+ throw error
600
+ }
601
+ if (!isInside(realRoot, real)) {
602
+ throw new WorkbenchError(403, `"${raw}" is a link that points outside the workspace root ${root}`, {
603
+ id: 'outside-root',
604
+ hint: 'links are followed only when the target stays inside the configured root.',
605
+ })
606
+ }
607
+ if (realStateRoot && isInside(realStateRoot, real)) {
608
+ throw new WorkbenchError(403, `"${raw}" is inside the plugin state directory`, {
609
+ id: 'protected-path',
610
+ hint: 'run state and access tokens are not readable through the panel.',
611
+ })
612
+ }
613
+ const relative = path.relative(realRoot, candidate).split(path.sep).join('/')
614
+ return { relative, absolute: real }
615
+ }
616
+
617
+ async function statTarget(input, wanted) {
618
+ const resolved = await resolvePath(input)
619
+ const stat = await fsp.stat(resolved.absolute)
620
+ if (wanted === 'dir' && !stat.isDirectory()) {
621
+ throw new WorkbenchError(400, `"${resolved.relative}" is not a directory`, { id: 'not-a-directory' })
622
+ }
623
+ if (wanted === 'file' && !stat.isFile()) {
624
+ throw new WorkbenchError(400, `"${resolved.relative}" is not a regular file`, { id: 'not-a-file' })
625
+ }
626
+ return { ...resolved, stat }
627
+ }
628
+
629
+ async function listTree(input) {
630
+ const { relative, absolute } = await statTarget(input ?? '.', 'dir')
631
+ const dirents = await fsp.readdir(absolute, { withFileTypes: true })
632
+ const entries = []
633
+ for (const dirent of dirents) {
634
+ if (entries.length >= TREE_LIMIT) break
635
+ const childAbs = path.join(absolute, dirent.name)
636
+ if (realStateRoot && isInside(realStateRoot, childAbs)) continue
637
+ const childRel = relative ? `${relative}/${dirent.name}` : dirent.name
638
+ if (dirent.isDirectory()) {
639
+ entries.push({ name: dirent.name, path: childRel, type: 'dir' })
640
+ continue
641
+ }
642
+ if (dirent.isSymbolicLink()) {
643
+ entries.push({ name: dirent.name, path: childRel, type: 'link' })
644
+ continue
645
+ }
646
+ if (!dirent.isFile()) continue
647
+ let stat = null
648
+ try {
649
+ stat = await fsp.stat(childAbs)
650
+ } catch {
651
+ // A file removed between readdir and stat is left out.
652
+ }
653
+ entries.push({
654
+ name: dirent.name,
655
+ path: childRel,
656
+ type: 'file',
657
+ size: stat?.size ?? null,
658
+ mtimeMs: stat?.mtimeMs ?? null,
659
+ })
660
+ }
661
+ entries.sort((a, b) => (a.type === b.type ? a.name.localeCompare(b.name) : a.type === 'dir' ? -1 : b.type === 'dir' ? 1 : 0))
662
+ return { path: relative, entries, truncated: dirents.length > entries.length }
663
+ }
664
+
665
+ async function readFileInfo(input) {
666
+ const { relative, absolute, stat } = await statTarget(input, 'file')
667
+ if (stat.size > MAX_EDIT_BYTES) {
668
+ return {
669
+ path: relative,
670
+ size: stat.size,
671
+ mtimeMs: stat.mtimeMs,
672
+ readOnly: 'too-large',
673
+ note: `this file is ${stat.size} bytes, above the ${MAX_EDIT_BYTES}-byte edit limit; the panel will not open it`,
674
+ content: null,
675
+ hash: null,
676
+ }
677
+ }
678
+ const buffer = await fsp.readFile(absolute)
679
+ if (looksBinary(buffer)) {
680
+ return {
681
+ path: relative,
682
+ size: stat.size,
683
+ mtimeMs: stat.mtimeMs,
684
+ readOnly: 'binary',
685
+ note: 'this looks like a binary file, so it is shown as metadata only',
686
+ content: null,
687
+ hash: sha256(buffer),
688
+ }
689
+ }
690
+ return {
691
+ path: relative,
692
+ size: stat.size,
693
+ mtimeMs: stat.mtimeMs,
694
+ readOnly: null,
695
+ note: null,
696
+ content: buffer.toString('utf8'),
697
+ hash: sha256(buffer),
698
+ }
699
+ }
700
+
701
+ async function preview(body) {
702
+ const content = body?.content
703
+ if (typeof content !== 'string') {
704
+ throw new WorkbenchError(400, 'content must be a string', { id: 'bad-content' })
705
+ }
706
+ const info = await readFileInfo(body.path)
707
+ if (info.readOnly) {
708
+ throw new WorkbenchError(409, info.note, { id: `read-only-${info.readOnly}` })
709
+ }
710
+ const diff = createUnifiedDiff(info.content, content, { path: info.path })
711
+ return { path: info.path, diff, stats: diffStats(diff), identical: diff === '' }
712
+ }
713
+
714
+ async function save(body) {
715
+ const content = body?.content
716
+ if (typeof content !== 'string') {
717
+ throw new WorkbenchError(400, 'content must be a string', { id: 'bad-content' })
718
+ }
719
+ const { relative, absolute, stat } = await statTarget(body.path, 'file')
720
+ if (stat.size > MAX_EDIT_BYTES) {
721
+ throw new WorkbenchError(409, `"${relative}" is above the ${MAX_EDIT_BYTES}-byte edit limit`, {
722
+ id: 'read-only-too-large',
723
+ })
724
+ }
725
+ const current = await fsp.readFile(absolute)
726
+ if (looksBinary(current)) {
727
+ throw new WorkbenchError(409, `"${relative}" is a binary file; the panel cannot edit it`, { id: 'read-only-binary' })
728
+ }
729
+ if (typeof body.expectedHash !== 'string' || !body.expectedHash) {
730
+ throw new WorkbenchError(400, 'expectedHash is required; open the file first so the panel can detect external edits', {
731
+ id: 'missing-baseline',
732
+ hint: 'reload the file in the editor before saving.',
733
+ })
734
+ }
735
+ if (!Number.isFinite(body.expectedMtimeMs)) {
736
+ throw new WorkbenchError(400, 'expectedMtimeMs is required; open the file first so the panel can detect external edits', {
737
+ id: 'missing-baseline',
738
+ hint: 'reload the file in the editor before saving.',
739
+ })
740
+ }
741
+ if (stat.mtimeMs !== body.expectedMtimeMs || sha256(current) !== body.expectedHash) {
742
+ throw new WorkbenchError(409, `"${relative}" changed on disk after it was opened; refusing to overwrite it`, {
743
+ id: 'external-change',
744
+ hint: 'reload the file to see the other change, then reapply your edit.',
745
+ })
746
+ }
747
+ const buffer = Buffer.from(content, 'utf8')
748
+ if (buffer.length > MAX_EDIT_BYTES) {
749
+ throw new WorkbenchError(413, `the new content is above the ${MAX_EDIT_BYTES}-byte edit limit`, {
750
+ id: 'save-too-large',
751
+ })
752
+ }
753
+ const directory = path.dirname(absolute)
754
+ const tmp = path.join(directory, `.${path.basename(absolute)}.${process.pid}.${++writeSeq}.wb.tmp`)
755
+ await fsp.writeFile(tmp, buffer, { flag: 'wx' })
756
+ try {
757
+ await fsp.rename(tmp, absolute)
758
+ } catch (error) {
759
+ await fsp.unlink(tmp).catch(() => {})
760
+ throw error
761
+ }
762
+ const after = await fsp.stat(absolute)
763
+ return {
764
+ path: relative,
765
+ size: after.size,
766
+ mtimeMs: after.mtimeMs,
767
+ hash: sha256(buffer),
768
+ }
769
+ }
770
+
771
+ async function listRuns({ limit } = {}) {
772
+ if (!store || typeof store.list !== 'function') return { runs: [], note: 'run storage is not available in this process' }
773
+ const rows = Math.max(1, Math.min(100, Number(limit) || 30))
774
+ const runs = await store.list()
775
+ return {
776
+ runs: runs.slice(0, rows).map(run => ({
777
+ id: run.id,
778
+ goal: run.goal,
779
+ status: run.status,
780
+ createdAt: run.createdAt,
781
+ finishedAt: run.finishedAt ?? null,
782
+ parentSessionId: run.parentSessionId ?? null,
783
+ changedFiles: Array.isArray(run.changes?.files) ? run.changes.files.length : null,
784
+ changesIncomplete: run.changes?.incomplete === true,
785
+ })),
786
+ }
787
+ }
788
+
789
+ async function readRun(runId) {
790
+ if (!store || typeof store.read !== 'function') {
791
+ throw new WorkbenchError(503, 'run storage is not available in this process', { id: 'no-store' })
792
+ }
793
+ let run = null
794
+ try {
795
+ run = await store.read(runId)
796
+ } catch (error) {
797
+ throw new WorkbenchError(500, `cannot read run ${runId}: ${error?.message ?? error}`, { id: 'run-read-failed' })
798
+ }
799
+ if (!run) throw new WorkbenchError(404, `no run ${runId} in this state directory`, { id: 'unknown-run' })
800
+ return run
801
+ }
802
+
803
+ async function runDiff(runId, requestedPath) {
804
+ const run = await readRun(runId)
805
+ const changes = Array.isArray(run.changes?.files) ? run.changes.files : []
806
+ const entry = changes.find(item => item.path === requestedPath)
807
+ if (!entry) {
808
+ throw new WorkbenchError(404, `"${requestedPath ?? ''}" is not recorded as changed by run ${runId}`, {
809
+ id: 'not-in-run',
810
+ hint: changes.length > 0 ? `changed files: ${changes.map(item => item.path).join(', ')}` : 'this run recorded no changed files',
811
+ })
812
+ }
813
+ const runRoot = typeof run.changes?.root === 'string' ? run.changes.root : null
814
+ if (!runRoot || !isInside(realRoot, runRoot) || !isInside(runRoot, realRoot)) {
815
+ return {
816
+ path: entry.path,
817
+ change: entry.change,
818
+ diff: null,
819
+ note: `the run recorded ${runRoot ?? 'no workspace root'}, which is not the root this panel serves`,
820
+ }
821
+ }
822
+ // A run record is local state, but a path in it still has to satisfy the
823
+ // same boundary as a path from the browser.
824
+ const candidate = path.resolve(realRoot, entry.path)
825
+ if (!isInside(realRoot, candidate) || (realStateRoot && isInside(realStateRoot, candidate))) {
826
+ return {
827
+ path: entry.path,
828
+ change: entry.change,
829
+ diff: null,
830
+ note: 'the run record points outside the workspace this panel serves',
831
+ }
832
+ }
833
+ const git = await gitPatch(realRoot, entry.path)
834
+ if (git.patch && git.patch.trim()) {
835
+ const patch = git.patch.endsWith('\n') ? git.patch : `${git.patch}\n`
836
+ return {
837
+ path: entry.path,
838
+ change: entry.change,
839
+ diff: patch,
840
+ stats: diffStats(patch),
841
+ baseline: 'git HEAD',
842
+ note: null,
843
+ }
844
+ }
845
+ if (git.available && await gitTracks(realRoot, entry.path)) {
846
+ return {
847
+ path: entry.path,
848
+ change: entry.change,
849
+ diff: '',
850
+ stats: { added: 0, removed: 0 },
851
+ baseline: 'git HEAD',
852
+ note: 'the file matches git HEAD, so the recorded change is no longer present in the working tree',
853
+ }
854
+ }
855
+
856
+ const current = await fsp.readFile(path.join(realRoot, entry.path)).catch(() => null)
857
+ if (!current) {
858
+ return {
859
+ path: entry.path,
860
+ change: entry.change,
861
+ diff: null,
862
+ note: `no baseline: ${git.reason ?? 'git has no copy and the file is gone'}`,
863
+ }
864
+ }
865
+ const diff = createUnifiedDiff('', current.toString('utf8'), { path: entry.path })
866
+ return {
867
+ path: entry.path,
868
+ change: entry.change,
869
+ diff,
870
+ stats: diffStats(diff),
871
+ baseline: null,
872
+ note: `no git baseline (${git.reason ?? 'the file is untracked'}); the diff shows the whole file as added`,
873
+ }
874
+ }
875
+
876
+ async function handle(req, res) {
877
+ try {
878
+ const parsed = new URL(req.url ?? '/', 'http://127.0.0.1')
879
+ const method = req.method ?? 'GET'
880
+ if (parsed.pathname === '/' || parsed.pathname === '/index.html') {
881
+ if (method !== 'GET') {
882
+ throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed', hint: ROUTE_HINT })
883
+ }
884
+ // The one page load may carry the token in the query string, because a
885
+ // browser cannot set an Authorization header on navigation. The page
886
+ // moves it into sessionStorage and strips it from the address bar.
887
+ authorize(req, { allowQuery: true })
888
+ sendText(res, 200, html, 'text/html; charset=utf-8', {
889
+ 'content-security-policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
890
+ + "connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
891
+ })
892
+ return
893
+ }
894
+
895
+ authorize(req)
896
+ const parts = parsed.pathname.split('/').filter(Boolean)
897
+ if (parts[0] !== 'api' || parts.length < 2) {
898
+ throw new WorkbenchError(404, `no route for ${method} ${parsed.pathname}`, { id: 'not-found', hint: ROUTE_HINT })
899
+ }
900
+
901
+ if (parts[1] === 'health' && parts.length === 2) {
902
+ if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
903
+ send(res, 200, {
904
+ ok: true,
905
+ data: {
906
+ service: 'dsh-superagent-workbench',
907
+ version,
908
+ root: realRoot,
909
+ pid: process.pid,
910
+ startedAt,
911
+ limits: { maxEditBytes: MAX_EDIT_BYTES },
912
+ },
913
+ })
914
+ return
915
+ }
916
+
917
+ if (parts[1] === 'tree' && parts.length === 2) {
918
+ if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
919
+ send(res, 200, { ok: true, data: await listTree(parsed.searchParams.get('path') ?? '.') })
920
+ return
921
+ }
922
+
923
+ if (parts[1] === 'file' && parts.length === 2) {
924
+ if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
925
+ send(res, 200, { ok: true, data: await readFileInfo(parsed.searchParams.get('path')) })
926
+ return
927
+ }
928
+
929
+ if (parts[1] === 'preview' && parts.length === 2) {
930
+ if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
931
+ send(res, 200, { ok: true, data: await preview(await readJson(req)) })
932
+ return
933
+ }
934
+
935
+ if (parts[1] === 'save' && parts.length === 2) {
936
+ if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
937
+ send(res, 200, { ok: true, data: await save(await readJson(req)) })
938
+ return
939
+ }
940
+
941
+ if (parts[1] === 'runs' && parts.length <= 3) {
942
+ if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
943
+ if (parts.length === 2) {
944
+ send(res, 200, { ok: true, data: await listRuns({ limit: parsed.searchParams.get('limit') }) })
945
+ return
946
+ }
947
+ let runId
948
+ try {
949
+ runId = decodeURIComponent(parts[2])
950
+ } catch {
951
+ throw new WorkbenchError(400, 'the run id is not valid percent-encoding', { id: 'bad-run-id' })
952
+ }
953
+ if (parts.length === 3) {
954
+ const run = await readRun(runId)
955
+ send(res, 200, {
956
+ ok: true,
957
+ data: {
958
+ id: run.id,
959
+ goal: run.goal,
960
+ status: run.status,
961
+ createdAt: run.createdAt,
962
+ finishedAt: run.finishedAt ?? null,
963
+ changes: run.changes ?? null,
964
+ },
965
+ })
966
+ return
967
+ }
968
+ }
969
+
970
+ if (parts[1] === 'runs' && parts.length === 4 && parts[3] === 'diff') {
971
+ if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
972
+ let runId
973
+ try {
974
+ runId = decodeURIComponent(parts[2])
975
+ } catch {
976
+ throw new WorkbenchError(400, 'the run id is not valid percent-encoding', { id: 'bad-run-id' })
977
+ }
978
+ const filePath = parsed.searchParams.get('path')
979
+ if (!filePath) throw new WorkbenchError(400, 'path is required', { id: 'missing-path' })
980
+ send(res, 200, { ok: true, data: await runDiff(runId, filePath) })
981
+ return
982
+ }
983
+
984
+ throw new WorkbenchError(404, `no route for ${method} ${parsed.pathname}`, { id: 'not-found', hint: ROUTE_HINT })
985
+ } catch (error) {
986
+ if (statusFor(error) >= 500) log(`workbench request failed: ${error?.message ?? error}`)
987
+ send(res, statusFor(error), errorPayload(error))
988
+ }
989
+ }
990
+
991
+ async function writeDiscovery() {
992
+ const doc = {
993
+ service: 'dsh-superagent-workbench',
994
+ version,
995
+ url: url(),
996
+ token,
997
+ root: realRoot,
998
+ pid: process.pid,
999
+ instanceId,
1000
+ startedAt,
1001
+ }
1002
+ const tmp = `${discoveryPath}.${process.pid}.${instanceId}.tmp`
1003
+ const handle = await fsp.open(tmp, 'wx', 0o600)
1004
+ try {
1005
+ await handle.writeFile(`${JSON.stringify(doc, null, 2)}\n`, 'utf8')
1006
+ } finally {
1007
+ await handle.close()
1008
+ }
1009
+ await fsp.rename(tmp, discoveryPath)
1010
+ try {
1011
+ await fsp.chmod(discoveryPath, 0o600)
1012
+ } catch {
1013
+ // Windows ignores most mode bits; the file's ACL still applies.
1014
+ }
1015
+ }
1016
+
1017
+ async function removeDiscovery() {
1018
+ try {
1019
+ const current = JSON.parse(await fsp.readFile(discoveryPath, 'utf8'))
1020
+ if (current?.instanceId !== instanceId) return
1021
+ await fsp.unlink(discoveryPath)
1022
+ } catch {
1023
+ // Already gone, or replaced by another instance.
1024
+ }
1025
+ await fsp.unlink(`${discoveryPath}.${process.pid}.${instanceId}.tmp`).catch(() => {})
1026
+ }
1027
+
1028
+ async function closeServer() {
1029
+ if (!server) return
1030
+ const instance = server
1031
+ server = null
1032
+ boundPort = null
1033
+ await new Promise(resolve => {
1034
+ instance.close(() => resolve())
1035
+ instance.closeAllConnections?.()
1036
+ })
1037
+ }
1038
+
1039
+ return {
1040
+ discoveryPath,
1041
+ get token() {
1042
+ return token
1043
+ },
1044
+ get port() {
1045
+ return boundPort
1046
+ },
1047
+ get url() {
1048
+ return boundPort ? url() : null
1049
+ },
1050
+
1051
+ /** Bind the loopback port, load the page, and publish the discovery file. */
1052
+ async start() {
1053
+ if (server) return { port: boundPort, url: url() }
1054
+ if (starting) return starting
1055
+ if (stopRequested) throw new Error('the workbench has been stopped; a new instance is required')
1056
+ const run = (async () => {
1057
+ realRoot = await fsp.realpath(root)
1058
+ realStateRoot = await fsp.realpath(stateRoot).catch(() => path.resolve(stateRoot))
1059
+ html = await fsp.readFile(new URL('../public/workbench.html', import.meta.url), 'utf8')
1060
+ const instance = createServer((req, res) => {
1061
+ handle(req, res).catch(error => {
1062
+ log(`workbench handler crashed: ${error?.message ?? error}`)
1063
+ send(res, 500, errorPayload(error))
1064
+ })
1065
+ })
1066
+ instance.requestTimeout = REQUEST_TIMEOUT_MS
1067
+ instance.headersTimeout = 10_000
1068
+ instance.keepAliveTimeout = 5_000
1069
+ instance.maxConnections = 64
1070
+ await new Promise((resolve, reject) => {
1071
+ const onError = error => reject(error)
1072
+ instance.once('error', onError)
1073
+ instance.listen(port, '127.0.0.1', () => {
1074
+ instance.off('error', onError)
1075
+ resolve()
1076
+ })
1077
+ })
1078
+ server = instance
1079
+ boundPort = instance.address().port
1080
+ if (stopRequested) {
1081
+ await closeServer()
1082
+ throw new Error('the workbench was stopped before it finished starting')
1083
+ }
1084
+ try {
1085
+ await writeDiscovery()
1086
+ } catch (error) {
1087
+ await closeServer()
1088
+ throw new Error(`cannot write the discovery file ${discoveryPath}: ${error?.message ?? error}`)
1089
+ }
1090
+ log(`workbench listening on ${url()} (token in ${discoveryPath})`)
1091
+ return { port: boundPort, url: url() }
1092
+ })()
1093
+ starting = run
1094
+ try {
1095
+ return await run
1096
+ } finally {
1097
+ if (starting === run) starting = null
1098
+ }
1099
+ },
1100
+
1101
+ /** Close the socket and remove this process's discovery file. */
1102
+ async stop() {
1103
+ stopRequested = true
1104
+ if (starting) {
1105
+ try {
1106
+ await starting
1107
+ } catch {
1108
+ // A start that failed has nothing to close.
1109
+ }
1110
+ }
1111
+ if (closing) return closing
1112
+ closing = (async () => {
1113
+ await closeServer()
1114
+ await removeDiscovery()
1115
+ })()
1116
+ return closing
1117
+ },
1118
+ }
1119
+ }