@maxbill/dsh-file-explorer 1.1.2 → 1.2.2

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/lib/index.js CHANGED
@@ -24,9 +24,10 @@
24
24
  * POST /transfer JSON {sources, target, mode: copy|move}
25
25
  */
26
26
 
27
- import { execFile } from 'node:child_process'
27
+ import { execFile, spawn } from 'node:child_process'
28
28
  import { once } from 'node:events'
29
- import { createWriteStream } from 'node:fs'
29
+ import { chmodSync, createWriteStream, existsSync } from 'node:fs'
30
+ import { createRequire } from 'node:module'
30
31
  import { access, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
31
32
  import { homedir, platform } from 'node:os'
32
33
  import { pathToFileURL } from 'node:url'
@@ -1029,6 +1030,9 @@ const ROUTES = [
1029
1030
  { suffix: '/git', methods: ['GET'] },
1030
1031
  { suffix: '/watch', methods: ['GET'] },
1031
1032
  { suffix: '/search', methods: ['GET'] },
1033
+ { suffix: '/term', methods: ['POST'] },
1034
+ { suffix: '/term-poll', methods: ['GET'] },
1035
+ { suffix: '/vendor', methods: ['GET'] },
1032
1036
  ]
1033
1037
 
1034
1038
  /**
@@ -1114,6 +1118,289 @@ async function sendRaw(res, target) {
1114
1118
  res.end(data)
1115
1119
  }
1116
1120
 
1121
+ /** A browser reaching us over loopback counts as local. */
1122
+ function isLoopback(req) {
1123
+ const hostHeader = String((req.headers && req.headers.host) || "").toLowerCase()
1124
+ const hostName = hostHeader.replace(/:\d+$/, "")
1125
+ return hostName === "127.0.0.1" || hostName === "localhost" || hostName === "[::1]" || hostName === "0.0.0.0" || hostName === ""
1126
+ }
1127
+
1128
+ /** Live terminal sessions, keyed by id. */
1129
+ const TERM_SESSIONS = new Map()
1130
+ let termSeq = 0
1131
+ const TERM_KEEP_BYTES = 300 * 1024
1132
+
1133
+ /** The shell to open, honouring $SHELL. */
1134
+ function termShell() {
1135
+ if (process.env.SHELL) return process.env.SHELL
1136
+ if (platform() === "win32") return process.env.COMSPEC || "cmd.exe"
1137
+ return "/bin/bash"
1138
+ }
1139
+
1140
+ /**
1141
+ * Python bridge that runs the shell behind a real pty. macOS script(1) needs
1142
+ * its own stdin to be a terminal, which it is not inside the DSH host, so a
1143
+ * small pty.fork relay is used instead. Resize travels over fd 3.
1144
+ */
1145
+ const TERM_PY = [
1146
+ "import os, pty, sys, select, fcntl, termios, struct",
1147
+ "shell, rows, cols = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])",
1148
+ "pid, fd = pty.fork()",
1149
+ "if pid == 0:",
1150
+ " os.execvpe(shell, [shell, \"-l\"], os.environ)",
1151
+ "def setsize(r, c):",
1152
+ " try:",
1153
+ " fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack(\"HHHH\", r, c, 0, 0))",
1154
+ " except OSError:",
1155
+ " pass",
1156
+ "setsize(rows, cols)",
1157
+ "while True:",
1158
+ " r, _, _ = select.select([fd, 0, 3], [], [])",
1159
+ " if fd in r:",
1160
+ " try:",
1161
+ " data = os.read(fd, 65536)",
1162
+ " except OSError:",
1163
+ " break",
1164
+ " if not data:",
1165
+ " break",
1166
+ " os.write(1, data)",
1167
+ " if 0 in r:",
1168
+ " data = os.read(0, 65536)",
1169
+ " if not data:",
1170
+ " break",
1171
+ " os.write(fd, data)",
1172
+ " if 3 in r:",
1173
+ " line = os.read(3, 64).decode(\"utf8\", \"ignore\").strip()",
1174
+ " parts = line.split()",
1175
+ " if len(parts) == 2:",
1176
+ " setsize(int(parts[0]), int(parts[1]))",
1177
+ ].join(String.fromCharCode(10))
1178
+
1179
+ /** Locate a python3 that can import pty. */
1180
+ function termPython() {
1181
+ return process.env.DSH_PYTHON || "/usr/bin/python3"
1182
+ }
1183
+
1184
+ /** node-pty loaded on first use; null once it is known to be missing. */
1185
+ let termPtyModule = null
1186
+ let termPtyTried = false
1187
+
1188
+ /**
1189
+ * Load the optional pty backend. node-pty ships prebuilt binaries for
1190
+ * macOS and Windows, so nothing is compiled; the macOS spawn helper loses
1191
+ * its exec bit through some package managers, so it is repaired here.
1192
+ * @returns {object|null} the node-pty module, or null when unavailable.
1193
+ */
1194
+ function loadNodePty() {
1195
+ if (termPtyTried) return termPtyModule
1196
+ termPtyTried = true
1197
+ try {
1198
+ const require = createRequire(import.meta.url)
1199
+ const loaded = require("node-pty")
1200
+ try {
1201
+ const pkg = require.resolve("node-pty/package.json")
1202
+ const root = dirname(pkg)
1203
+ for (const rel of ["prebuilds/" + process.platform + "-" + process.arch + "/spawn-helper", "build/Release/spawn-helper"]) {
1204
+ const helper = join(root, rel)
1205
+ if (existsSync(helper)) {
1206
+ try { chmodSync(helper, 0o755) } catch {}
1207
+ }
1208
+ }
1209
+ } catch {}
1210
+ termPtyModule = loaded
1211
+ } catch {
1212
+ termPtyModule = null
1213
+ }
1214
+ return termPtyModule
1215
+ }
1216
+
1217
+ /**
1218
+ * Start a shell under node-pty.
1219
+ * @param {string} shell - login shell
1220
+ * @param {number} cols - columns
1221
+ * @param {number} rows - rows
1222
+ * @param {string} cwd - working directory
1223
+ * @returns {object|null} pty handle or null
1224
+ */
1225
+ function termSpawnNodePty(shell, cols, rows, cwd) {
1226
+ const module = loadNodePty()
1227
+ if (!module) return null
1228
+ const args = platform() === "win32" ? [] : ["-l"]
1229
+ return module.spawn(shell, args, {
1230
+ name: "xterm-256color",
1231
+ cols,
1232
+ rows,
1233
+ cwd,
1234
+ env: { ...process.env, TERM: "xterm-256color", COLUMNS: String(cols), LINES: String(rows) },
1235
+ })
1236
+ }
1237
+
1238
+ /**
1239
+ * The pty bridge when python3 is available, otherwise the plain shell.
1240
+ * @param {string} shell - login shell
1241
+ * @param {number} rows - initial rows
1242
+ * @param {number} cols - initial cols
1243
+ * @returns {object} spawn arguments
1244
+ */
1245
+ function termCommand(shell, rows, cols) {
1246
+ if (platform() !== "win32") {
1247
+ return { command: termPython(), args: ["-c", TERM_PY, shell, String(rows), String(cols)], pty: true }
1248
+ }
1249
+ return { command: shell, args: [], pty: false }
1250
+ }
1251
+ /** Append output to a session, dropping the oldest bytes past the cap. */
1252
+ function termPush(session, text) {
1253
+ const clean = String(text)
1254
+ if (!clean) return
1255
+ session.chunks.push({ seq: session.nextSeq++, text: clean })
1256
+ session.bytes += clean.length
1257
+ while (session.bytes > TERM_KEEP_BYTES && session.chunks.length > 1) {
1258
+ const dropped = session.chunks.shift()
1259
+ session.bytes -= dropped.text.length
1260
+ }
1261
+ }
1262
+
1263
+ /** Close shells nobody has looked at for half an hour. */
1264
+ const TERM_IDLE_MS = 30 * 60 * 1000
1265
+ const TERM_SWEEP = setInterval(() => {
1266
+ const now = Date.now()
1267
+ for (const [id, session] of TERM_SESSIONS) {
1268
+ if (session.exited || now - session.lastSeen > TERM_IDLE_MS) termClose(id)
1269
+ }
1270
+ }, 60 * 1000)
1271
+ if (typeof TERM_SWEEP.unref === "function") TERM_SWEEP.unref()
1272
+
1273
+ /** Close one session and its process group. */
1274
+ function termClose(id) {
1275
+ const session = TERM_SESSIONS.get(id)
1276
+ if (!session) return false
1277
+ try { session.kill() } catch {}
1278
+ TERM_SESSIONS.delete(id)
1279
+ return true
1280
+ }
1281
+
1282
+ /**
1283
+ * Open a shell at a directory and remember its output. node-pty is used when
1284
+ * it loaded (real pty on macOS, Linux and Windows), with the python bridge
1285
+ * and finally plain pipes as fallbacks.
1286
+ */
1287
+ async function termOpen(body) {
1288
+ const cwd = await safePath(body.cwd)
1289
+ const info = await stat(cwd)
1290
+ if (!info.isDirectory()) throw new RouteError(400, "cwd is not a folder")
1291
+ const cols = Math.max(20, Math.min(400, Number(body.cols) || 80))
1292
+ const rows = Math.max(5, Math.min(200, Number(body.rows) || 24))
1293
+ const shell = termShell()
1294
+ const id = "t" + (termSeq += 1) + "-" + Date.now().toString(36)
1295
+ const session = {
1296
+ id, chunks: [], nextSeq: 0, bytes: 0, exited: false, code: null,
1297
+ cwd, pty: false, engine: "pipe", cols, rows, lastSeen: Date.now(),
1298
+ write: () => {}, resize: () => {}, kill: () => {},
1299
+ }
1300
+
1301
+ let handle = null
1302
+ try { handle = termSpawnNodePty(shell, cols, rows, cwd) } catch { handle = null }
1303
+ if (handle) {
1304
+ session.engine = "node-pty"
1305
+ session.pty = true
1306
+ handle.onData((data) => termPush(session, data))
1307
+ handle.onExit(({ exitCode }) => {
1308
+ session.exited = true
1309
+ session.code = exitCode
1310
+ termPush(session, "\r\n[进程已退出 " + (exitCode === null ? "" : exitCode) + "]\r\n")
1311
+ })
1312
+ session.write = (data) => { try { handle.write(data) } catch {} }
1313
+ session.resize = (c, r) => { try { handle.resize(c, r) } catch {} }
1314
+ session.kill = () => { try { handle.kill() } catch {} }
1315
+ } else {
1316
+ const spec = termCommand(shell, rows, cols)
1317
+ const proc = spawn(spec.command, spec.args, {
1318
+ cwd,
1319
+ env: { ...process.env, TERM: "xterm-256color", COLUMNS: String(cols), LINES: String(rows) },
1320
+ stdio: ["pipe", "pipe", "pipe", "pipe"],
1321
+ })
1322
+ session.pty = spec.pty
1323
+ session.engine = spec.pty ? "python" : "pipe"
1324
+ const control = spec.pty ? proc.stdio[3] : null
1325
+ proc.stdout.setEncoding("utf8")
1326
+ proc.stderr.setEncoding("utf8")
1327
+ proc.stdout.on("data", (chunk) => termPush(session, chunk))
1328
+ proc.stderr.on("data", (chunk) => termPush(session, chunk))
1329
+ proc.on("exit", (code) => {
1330
+ session.exited = true
1331
+ session.code = code
1332
+ termPush(session, "\r\n[进程已退出 " + (code === null ? "" : code) + "]\r\n")
1333
+ })
1334
+ proc.on("error", (error) => termPush(session, "\r\n[无法启动终端: " + (error && error.message) + "]\r\n"))
1335
+ session.write = (data) => { try { proc.stdin.write(data) } catch {} }
1336
+ session.resize = (c, r) => {
1337
+ if (control) { try { control.write(String(r) + " " + String(c) + "\n") } catch {} }
1338
+ }
1339
+ session.kill = () => {
1340
+ try { proc.kill("SIGHUP") } catch {}
1341
+ try { proc.kill("SIGKILL") } catch {}
1342
+ }
1343
+ }
1344
+
1345
+ TERM_SESSIONS.set(session.id, session)
1346
+ if (TERM_SESSIONS.size > 3) {
1347
+ const oldest = TERM_SESSIONS.keys().next().value
1348
+ if (oldest !== session.id) termClose(oldest)
1349
+ }
1350
+ return { id: session.id, pty: session.pty, engine: session.engine, shell, cwd }
1351
+ }
1352
+ /** One POST on /term: open, input, resize or close. */
1353
+ async function handleTerm(req) {
1354
+ const raw = await readBody(req)
1355
+ let body = {}
1356
+ try { body = raw.length > 0 ? JSON.parse(raw.toString("utf8")) : {} } catch { throw new RouteError(400, "malformed JSON") }
1357
+ const action = String(body.action || "")
1358
+ if (action === "open") return termOpen(body)
1359
+ const session = TERM_SESSIONS.get(String(body.id || ""))
1360
+ if (!session) throw new RouteError(404, "terminal is gone")
1361
+ if (action === "input") {
1362
+ session.write(String(body.data || ""))
1363
+ return { ok: true }
1364
+ }
1365
+ if (action === "resize") {
1366
+ session.cols = Number(body.cols) || null
1367
+ session.rows = Number(body.rows) || null
1368
+ session.resize(session.cols || 80, session.rows || 24)
1369
+ return { ok: true, pty: session.pty }
1370
+ }
1371
+ if (action === "close") return { ok: termClose(session.id) }
1372
+ throw new RouteError(400, "unknown action")
1373
+ }
1374
+
1375
+ /** Output that arrived after the given sequence number. */
1376
+ function pollTerm(id, since) {
1377
+ const session = TERM_SESSIONS.get(id)
1378
+ if (!session) return { gone: true, data: "", since, exited: true }
1379
+ session.lastSeen = Date.now()
1380
+ const parts = []
1381
+ for (const chunk of session.chunks) {
1382
+ if (chunk.seq >= since) parts.push(chunk.text)
1383
+ }
1384
+ return { gone: false, data: parts.join(""), since: session.nextSeq, exited: session.exited, code: session.code }
1385
+ }
1386
+
1387
+ /** Serve the terminal renderer from our own dependency. */
1388
+ async function sendVendor(res, name) {
1389
+ const allowed = { "xterm.js": "lib/xterm.js", "xterm.css": "css/xterm.css" }
1390
+ const rel = allowed[name]
1391
+ if (!rel) throw new RouteError(404, "unknown asset")
1392
+ const file = new URL("../node_modules/@xterm/xterm/" + rel, import.meta.url)
1393
+ let data
1394
+ try {
1395
+ data = await readFile(file)
1396
+ } catch {
1397
+ throw new RouteError(404, "xterm is not installed")
1398
+ }
1399
+ const type = name.endsWith(".css") ? "text/css; charset=utf-8" : "text/javascript; charset=utf-8"
1400
+ res.writeHead(200, { "Content-Type": type, "Content-Length": data.length, "Cache-Control": "no-store" })
1401
+ res.end(data)
1402
+ }
1403
+
1117
1404
  function mimeOf(target) {
1118
1405
  const ext = extname(target).toLowerCase()
1119
1406
  const table = {
@@ -1285,6 +1572,20 @@ async function handleRequest(req, res) {
1285
1572
  ))
1286
1573
  return
1287
1574
  }
1575
+ if (route === '/term' && method === 'POST') {
1576
+ if (!isLoopback(req)) throw new RouteError(403, 'terminal is desktop-only')
1577
+ send(res, 200, await handleTerm(req))
1578
+ return
1579
+ }
1580
+ if (route === '/term-poll' && method === 'GET') {
1581
+ if (!isLoopback(req)) throw new RouteError(403, 'terminal is desktop-only')
1582
+ send(res, 200, pollTerm(url.searchParams.get('id') || '', Number(url.searchParams.get('since') || 0)))
1583
+ return
1584
+ }
1585
+ if (route === '/vendor' && method === 'GET') {
1586
+ await sendVendor(res, url.searchParams.get('name') || '')
1587
+ return
1588
+ }
1288
1589
  if (route === '/download' && method === 'GET') {
1289
1590
  await sendAttachment(res, await safePath(path))
1290
1591
  return
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maxbill/dsh-file-explorer",
3
- "version": "1.1.2",
3
+ "version": "1.2.2",
4
4
  "description": "文件管理器 — 浏览、预览并直接用起来:文件夹一键变成工作区,文档一键加进当前对话 · A file manager for DeepSeek Harness that turns folders into workspaces and documents into conversation attachments",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -63,5 +63,11 @@
63
63
  "client": {
64
64
  "platform": "web"
65
65
  }
66
+ },
67
+ "dependencies": {
68
+ "@xterm/xterm": "^5.5.0"
69
+ },
70
+ "optionalDependencies": {
71
+ "node-pty": "^1.1.0"
66
72
  }
67
73
  }
package/screenshots.json CHANGED
@@ -1,4 +1,5 @@
1
1
  [
2
+ "docs/terminal-panel.png",
2
3
  "docs/panel.png",
3
4
  "docs/icon-view.png",
4
5
  "docs/grouped.png",