dsh-remote-vs 0.11.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { a as pushPipeline, c as require_lib, d as ensurePrivateDir, f as keysDir, i as probe, l as aliasRoot, o as seedHelperCache, p as storePath, r as helperAvailability, s as RemoteFiles, t as RemoteWorlds, u as dshHome } from "./worlds-a8nqW9mi.js";
1
+ import { a as pushPipeline, c as attachmentHeader, d as dshHome, f as ensurePrivateDir, i as probe, l as require_lib, m as storePath, o as seedHelperCache, p as keysDir, r as helperAvailability, s as RemoteFiles, t as RemoteWorlds, u as aliasRoot } from "./worlds-C6Xha1mQ.js";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, writeSync } from "node:fs";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
- import { dirname, join } from "node:path";
5
+ import { dirname, join, posix } from "node:path";
6
6
  import { homedir } from "node:os";
7
7
  import { StringDecoder } from "node:string_decoder";
8
8
  import { fileURLToPath } from "node:url";
@@ -346,6 +346,18 @@ const CHANNEL_LIMIT = 6;
346
346
  * readable error that tells the user to retry.
347
347
  */
348
348
  const CHANNEL_WAIT_MS = 3e4;
349
+ /**
350
+ * Idle time after which the shared BROWSE SFTP session is closed.
351
+ *
352
+ * Browsing is bursty (open a folder, look around, edit for a while, browse
353
+ * again), so a channel that survives only the burst costs one channel-open
354
+ * round trip per burst and saves one per request inside it. Two minutes covers
355
+ * the burst without keeping a channel slot parked for a five-minute pause. The
356
+ * slot it holds is the one a per-request session took, so peak channel usage
357
+ * against the server's MaxSessions does not change; the parked-slot trade-off
358
+ * is spelled out in withBrowseSftp's docstring.
359
+ */
360
+ const BROWSE_IDLE_MS = 120 * 1e3;
349
361
  var RemotePool = class {
350
362
  store;
351
363
  conns = /* @__PURE__ */ new Map();
@@ -355,11 +367,14 @@ var RemotePool = class {
355
367
  setsidProbes = /* @__PURE__ */ new Map();
356
368
  /** Per-alias channel slots and the queue waiting for one (see acquireSlot). */
357
369
  slots = /* @__PURE__ */ new Map();
370
+ /** Per-alias BROWSE SFTP session (see withBrowseSftp). */
371
+ browsed = /* @__PURE__ */ new Map();
358
372
  constructor(store) {
359
373
  this.store = store;
360
374
  }
361
375
  /** Drop one pooled connection (call after host update/delete). */
362
376
  drop(alias) {
377
+ this.evictBrowse(alias);
363
378
  const pooled = this.conns.get(alias);
364
379
  this.setsidProbes.delete(alias);
365
380
  if (pooled === void 0) return;
@@ -686,12 +701,7 @@ var RemotePool = class {
686
701
  }
687
702
  this.hold(alias);
688
703
  try {
689
- const sftp = await withDeadline(new Promise((resolve, reject) => {
690
- conn.sftp((error, session) => {
691
- if (error !== void 0 && error !== null) reject(error);
692
- else resolve(session);
693
- });
694
- }), SFTP_OP_TIMEOUT_MS, `SFTP session open timed out after ${SFTP_OP_TIMEOUT_MS / 1e3}s`);
704
+ const sftp = await this.openSession(conn);
695
705
  try {
696
706
  const limit = opts.timeoutMs ?? SFTP_OP_TIMEOUT_MS;
697
707
  if (limit <= 0) return await fn(sftp);
@@ -706,6 +716,111 @@ var RemotePool = class {
706
716
  this.releaseSlot(alias);
707
717
  }
708
718
  }
719
+ /**
720
+ * Run one bulk-transfer callback with a dedicated SFTP session, plus extra
721
+ * channel windows on demand (`addChannel`).
722
+ *
723
+ * Why extra channels: ssh2 (Channel.js `MAX_WINDOW`) and OpenSSH cap ONE SSH
724
+ * channel's window at 2 MiB, so a single channel can never hold 8 MiB of READs
725
+ * in flight however much concurrency the caller asks for; the rest queue
726
+ * client-side. Each extra session is another 2 MiB window. Measured against a
727
+ * real host (96 MiB file, 256 KiB chunks, same total concurrency):
728
+ * 1 channel 28.6 MiB/s, 2 channels 46.1, 4 channels 51.3 — two channels take
729
+ * most of the gain, four cost twice the channels for little more. Uploads
730
+ * showed no such gain (server-side write bound: 46.0 → 50.4 MiB/s), so only
731
+ * downloads spread out.
732
+ *
733
+ * `addChannel` is best-effort and late on purpose: a small download must not
734
+ * pay for a second channel, so the caller opens one only after it has the
735
+ * size. It never queues for a channel slot (a 30 s wait would stall a body that
736
+ * is already streaming) and a late call after the callback settled is a no-op.
737
+ * Every session opened here is closed, and every slot/hold released, when the
738
+ * callback settles — including a partially successful `addChannel`.
739
+ *
740
+ * There is no wall-clock deadline of its own: streaming is progress-bounded by
741
+ * the caller, and the caller also bounds the one-shot SFTP calls it makes
742
+ * around the stream (metadata phase, optional channel opens), because nothing
743
+ * there produces progress to watch.
744
+ */
745
+ async withTransferSftp(alias, fn) {
746
+ const sessions = [];
747
+ let slots = 0;
748
+ let holds = 0;
749
+ /** Set when the callback settles: a late `addChannel` must not leak resources. */
750
+ let closed = false;
751
+ let conn;
752
+ try {
753
+ await this.acquireSlot(alias);
754
+ slots += 1;
755
+ conn = await this.acquire(alias);
756
+ this.hold(alias);
757
+ holds += 1;
758
+ sessions.push(await this.openSession(conn));
759
+ const addChannel = async () => {
760
+ if (closed) return void 0;
761
+ if (!this.tryAcquireSlot(alias)) return void 0;
762
+ slots += 1;
763
+ this.hold(alias);
764
+ holds += 1;
765
+ try {
766
+ const extra = await this.openSession(conn);
767
+ if (closed) {
768
+ try {
769
+ extra.end();
770
+ } catch {}
771
+ return;
772
+ }
773
+ sessions.push(extra);
774
+ return extra;
775
+ } catch {
776
+ return;
777
+ }
778
+ };
779
+ return await fn(sessions[0], addChannel);
780
+ } finally {
781
+ closed = true;
782
+ for (const session of sessions) try {
783
+ session.end();
784
+ } catch {}
785
+ for (let i = 0; i < holds; i += 1) this.release(alias);
786
+ for (let i = 0; i < slots; i += 1) this.releaseSlot(alias);
787
+ }
788
+ }
789
+ /**
790
+ * Run one callback on this alias's long-lived BROWSE SFTP session.
791
+ *
792
+ * Why: every list/stat/read used to open its own SFTP session, which is a
793
+ * whole channel-open round trip BEFORE the operation's own round trip. A single
794
+ * folder open is one list plus a stat per entry the explorer probes, and the
795
+ * panel's revision refresh re-lists every open directory, so that open/close
796
+ * churn sat directly on the click-to-pixels path. The session is shared by
797
+ * every browse request for the alias; ssh2 multiplexes concurrent requests
798
+ * over one channel by packet id (the same request map fastGet/fastPut use).
799
+ *
800
+ * Only read-only browse operations use it (`RemoteFiles.list/stat/read`):
801
+ * writes, uploads and downloads keep their own short-lived session, so a
802
+ * mutation never inherits a channel that a previous request may have left in
803
+ * an odd state.
804
+ *
805
+ * The session holds one channel slot and one connection hold while it exists,
806
+ * which is what a per-request session took too, so peak channel usage against
807
+ * the server's MaxSessions does not change. The trade-off is that the slot
808
+ * stays PARKED for up to `BROWSE_IDLE_MS` after the last request: the extras a
809
+ * bulk transfer asks for use `tryAcquireSlot`, so they never wait on it.
810
+ */
811
+ async withBrowseSftp(alias, fn, opts = {}) {
812
+ const lease = await this.leaseBrowse(alias);
813
+ const limit = opts.timeoutMs ?? SFTP_OP_TIMEOUT_MS;
814
+ try {
815
+ if (limit <= 0) return await fn(lease.sftp);
816
+ return await withDeadline(fn(lease.sftp), limit, `SFTP operation on ${alias} timed out after ${limit / 1e3}s`);
817
+ } catch (error) {
818
+ if (error instanceof DeadlineError) lease.state.stale = true;
819
+ throw error;
820
+ } finally {
821
+ this.touchBrowse(alias, lease.state);
822
+ }
823
+ }
709
824
  /** Upload one local file to an absolute remote path (parallel fastPut). */
710
825
  async putFile(alias, localPath, remotePath) {
711
826
  await this.withSftp(alias, async (sftp) => {
@@ -730,15 +845,164 @@ var RemotePool = class {
730
845
  timer.unref?.();
731
846
  };
732
847
  arm();
733
- sftp.fastPut(localPath, remotePath, { step: () => {
734
- arm();
735
- } }, (error) => {
848
+ sftp.fastPut(localPath, remotePath, {
849
+ concurrency: 64,
850
+ chunkSize: 256 * 1024,
851
+ step: () => {
852
+ arm();
853
+ }
854
+ }, (error) => {
736
855
  finish(error === void 0 || error === null ? void 0 : new Error(error.message));
737
856
  });
738
857
  });
739
858
  }, { timeoutMs: 0 });
740
859
  }
741
860
  /**
861
+ * Open one SFTP session under its own deadline.
862
+ *
863
+ * ssh2 has no channel-open timeout: a server that never answers leaves this
864
+ * promise pending forever, which pins the connection's hold count and blocks
865
+ * idle re-arming (the "SSH looks dead" symptom) while the HTTP request hangs.
866
+ */
867
+ openSession(conn) {
868
+ return withDeadline(new Promise((resolve, reject) => {
869
+ conn.sftp((error, session) => {
870
+ if (error !== void 0 && error !== null) reject(error);
871
+ else resolve(session);
872
+ });
873
+ }), SFTP_OP_TIMEOUT_MS, `SFTP session open timed out after ${SFTP_OP_TIMEOUT_MS / 1e3}s`);
874
+ }
875
+ /**
876
+ * Take the browse channel for one operation (open it on first use).
877
+ *
878
+ * The returned lease counts as one in-flight operation; the caller's `finally`
879
+ * calls touchBrowse(). An open failure takes neither a slot nor a hold, so a
880
+ * failed host does not leave the pool's accounting skewed.
881
+ */
882
+ async leaseBrowse(alias) {
883
+ const state = this.browseState(alias);
884
+ if (state.stale) {
885
+ this.evictBrowse(alias, state);
886
+ return this.leaseBrowse(alias);
887
+ }
888
+ if (state.idle !== void 0) {
889
+ clearTimeout(state.idle);
890
+ state.idle = void 0;
891
+ }
892
+ if (state.session !== void 0) {
893
+ state.active += 1;
894
+ return {
895
+ state,
896
+ sftp: state.session
897
+ };
898
+ }
899
+ if (state.opening === void 0) state.opening = this.openBrowse(alias, state);
900
+ const opening = state.opening;
901
+ try {
902
+ const sftp = await opening;
903
+ state.active += 1;
904
+ return {
905
+ state,
906
+ sftp
907
+ };
908
+ } finally {
909
+ if (state.opening === opening) state.opening = void 0;
910
+ }
911
+ }
912
+ /**
913
+ * Open the browse session: a channel slot + a connection hold + the SFTP
914
+ * session itself, all released together by evictBrowse().
915
+ */
916
+ async openBrowse(alias, state) {
917
+ await this.acquireSlot(alias);
918
+ let conn;
919
+ try {
920
+ conn = await this.acquire(alias);
921
+ } catch (error) {
922
+ this.releaseSlot(alias);
923
+ throw error;
924
+ }
925
+ this.hold(alias);
926
+ state.leased = true;
927
+ try {
928
+ const sftp = await this.openSession(conn);
929
+ if (this.browsed.get(alias) !== state || !state.leased) {
930
+ try {
931
+ sftp.end();
932
+ } catch {}
933
+ throw new Error(`host ${alias} was disconnected while opening the browse session`);
934
+ }
935
+ state.session = sftp;
936
+ sftp.on("close", () => {
937
+ if (state.session !== sftp) return;
938
+ state.session = void 0;
939
+ this.evictBrowse(alias, state);
940
+ });
941
+ return sftp;
942
+ } catch (error) {
943
+ this.evictBrowse(alias, state);
944
+ throw error;
945
+ }
946
+ }
947
+ /** One completed browse operation: idle-close the channel when it is unused. */
948
+ touchBrowse(alias, state) {
949
+ if (state.active > 0) state.active -= 1;
950
+ if (state.active > 0) return;
951
+ if (state.stale) {
952
+ this.evictBrowse(alias, state);
953
+ return;
954
+ }
955
+ if (state.idle !== void 0) clearTimeout(state.idle);
956
+ state.idle = setTimeout(() => {
957
+ state.idle = void 0;
958
+ if (state.active === 0) this.evictBrowse(alias, state);
959
+ }, BROWSE_IDLE_MS);
960
+ state.idle.unref?.();
961
+ }
962
+ /**
963
+ * Close the browse session and give its slot and hold back. Idempotent; every
964
+ * way the session can end (idle, open failure, channel close, connection drop)
965
+ * goes through here so the accounting cannot drift.
966
+ *
967
+ * `expected` ties the eviction to ONE session object: a timer or a channel
968
+ * `close` event that fires after the state was already replaced must not close
969
+ * its successor. Callers that end the connection (drop/dispose) omit it.
970
+ */
971
+ evictBrowse(alias, expected) {
972
+ const state = this.browsed.get(alias);
973
+ if (state === void 0) return;
974
+ if (expected !== void 0 && state !== expected) return;
975
+ this.browsed.delete(alias);
976
+ if (state.idle !== void 0) {
977
+ clearTimeout(state.idle);
978
+ state.idle = void 0;
979
+ }
980
+ const session = state.session;
981
+ state.session = void 0;
982
+ if (session !== void 0) try {
983
+ session.end();
984
+ } catch {}
985
+ if (state.leased) {
986
+ state.leased = false;
987
+ this.release(alias);
988
+ this.releaseSlot(alias);
989
+ }
990
+ }
991
+ browseState(alias) {
992
+ const existing = this.browsed.get(alias);
993
+ if (existing !== void 0) return existing;
994
+ const created = {
995
+ session: void 0,
996
+ opening: void 0,
997
+ active: 0,
998
+ stale: false,
999
+ leased: false,
1000
+ idle: void 0
1001
+ };
1002
+ this.browsed.set(alias, created);
1003
+ return created;
1004
+ }
1005
+ /**
742
1006
  * Take one channel slot for `alias`, waiting FIFO when the limit is reached.
743
1007
  * The wait is bounded: waiting forever behind a peer that never finishes is
744
1008
  * worse than a readable error naming the cause and what to do about it.
@@ -767,6 +1031,22 @@ var RemotePool = class {
767
1031
  state.queue.push(waiter);
768
1032
  });
769
1033
  }
1034
+ /**
1035
+ * Take one channel slot only if one is free RIGHT NOW; never queue.
1036
+ *
1037
+ * Optional work (a bulk transfer's second channel) must not wait behind
1038
+ * `CHANNEL_WAIT_MS` of other operations: a "best effort" extra channel that
1039
+ * delays the body of an already-streaming download by 30 s is worse than the
1040
+ * one channel the transfer would have used anyway. A queued waiter also blocks
1041
+ * the attempt on purpose — it has been waiting longer, and stealing its slot
1042
+ * would just move the wait.
1043
+ */
1044
+ tryAcquireSlot(alias) {
1045
+ const state = this.slotState(alias);
1046
+ if (state.active >= CHANNEL_LIMIT || state.queue.length > 0) return false;
1047
+ state.active += 1;
1048
+ return true;
1049
+ }
770
1050
  /** Give a slot back, handing it straight to the longest-waiting operation. */
771
1051
  releaseSlot(alias) {
772
1052
  const state = this.slots.get(alias);
@@ -1022,12 +1302,20 @@ function warnDetached(alias) {
1022
1302
  console.warn(`[dsh-remote-vs] exec timed out on ${alias}: the channel is closed but the remote command may still be running (no killable process group)`);
1023
1303
  }
1024
1304
  /**
1305
+ * An operation that ran out of its wall-clock budget.
1306
+ *
1307
+ * Tagged on purpose: callers have to tell "the remote never answered" from a real
1308
+ * remote failure (a missing path must not cost the session), and matching on the
1309
+ * message text would silently stop working the moment the template changed.
1310
+ */
1311
+ var DeadlineError = class extends Error {};
1312
+ /**
1025
1313
  * Reject when `promise` has not settled within `ms`, so a stalled remote
1026
1314
  * callback cannot keep a session (and its pooled connection) alive forever.
1027
1315
  */
1028
1316
  function withDeadline(promise, ms, message) {
1029
1317
  return new Promise((resolve, reject) => {
1030
- const timer = setTimeout(() => reject(new Error(message)), ms);
1318
+ const timer = setTimeout(() => reject(new DeadlineError(message)), ms);
1031
1319
  timer.unref?.();
1032
1320
  promise.then((value) => {
1033
1321
  clearTimeout(timer);
@@ -1137,6 +1425,12 @@ const REMOTE_API = {
1137
1425
  files: "/api/dsh-remote/files",
1138
1426
  /** Streaming binary upload: raw request body, host and path in the query. */
1139
1427
  upload: "/api/dsh-remote/upload",
1428
+ /** Streaming binary download: raw response body, host and path in the query. */
1429
+ download: "/api/dsh-remote/download",
1430
+ /** Streaming directory download: a remote `tar -czf -` of the directory. */
1431
+ downloadDir: "/api/dsh-remote/download-dir",
1432
+ /** Streaming multi-selection download: one remote tar of repeated `path` params. */
1433
+ downloadMany: "/api/dsh-remote/download-many",
1140
1434
  workspaces: "/api/dsh-remote/workspaces",
1141
1435
  deploy: "/api/dsh-remote/deploy",
1142
1436
  importSshConfig: "/api/dsh-remote/import-ssh-config",
@@ -1149,6 +1443,71 @@ const REMOTE_API = {
1149
1443
  /** What one live session changed on its remote host (the review panel). */
1150
1444
  changes: "/api/dsh-remote/changes"
1151
1445
  };
1446
+ /** Suggested/attachment file name for one multi-selection archive. */
1447
+ function selectionDownloadName(count) {
1448
+ return `selection-${count}.tar.gz`;
1449
+ }
1450
+ //#endregion
1451
+ //#region src/git-format.ts
1452
+ /** Wrap a value for POSIX sh single-quote context. */
1453
+ function shQuote(value) {
1454
+ return `'${value.replace(/'/g, `'\\''`)}'`;
1455
+ }
1456
+ //#endregion
1457
+ //#region src/archive.ts
1458
+ /**
1459
+ * Remote directory archiving for the download route.
1460
+ *
1461
+ * The archive is produced ON the remote host (`tar -czf -`) and streamed
1462
+ * straight into the HTTP response, so the Host never builds it in memory or
1463
+ * writes it to its own disk. Pure string builders (no fs, no exec) so the
1464
+ * download gate can pin the exact command shape.
1465
+ */
1466
+ /** Download file name for one archived directory. */
1467
+ function directoryArchiveName(dir) {
1468
+ const trimmed = String(dir).replace(/[\\/]+$/, "");
1469
+ const at = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
1470
+ const base = at < 0 ? trimmed : trimmed.slice(at + 1);
1471
+ return `${base === "" ? "root" : base}.tar.gz`;
1472
+ }
1473
+ /**
1474
+ * One POSIX shell command that writes the directory's gzip tar to stdout.
1475
+ *
1476
+ * The member name is prefixed with `./` so a directory whose name starts with
1477
+ * `-` cannot be read as a tar option; `-C` names the parent instead of relying
1478
+ * on a shell `cd`, and both paths are single-quoted (`shQuote`) so spaces,
1479
+ * quotes and `$()` in a real path cannot escape into the command.
1480
+ */
1481
+ function directoryArchiveCommand(dir) {
1482
+ const path = String(dir).replace(/\\/g, "/").replace(/\/+$/, "");
1483
+ if (path === "" || path === "/") throw new Error("refusing to archive the remote root");
1484
+ if (!path.startsWith("/")) throw new Error("remote path must be absolute");
1485
+ const parent = posix.dirname(path);
1486
+ const name = posix.basename(path);
1487
+ return `tar -czf - -C ${shQuote(parent)} ${shQuote(`./${name}`)}`;
1488
+ }
1489
+ /**
1490
+ * One POSIX shell command archiving several selected paths to stdout.
1491
+ *
1492
+ * GNU tar accepts one `-C` before each member, so every entry is stored as its
1493
+ * own bare `./name` while keeping its real parent on the remote side; that is
1494
+ * what lets a selection span several directories (mixed files and directories
1495
+ * are fine — tar recurses into directories). Two entries with the same basename
1496
+ * from different directories collide inside the archive by design: the
1497
+ * alternative would be a synthetic directory tree the remote never had.
1498
+ */
1499
+ function selectionArchiveCommand(paths) {
1500
+ if (paths.length === 0) throw new Error("refusing to archive an empty selection");
1501
+ if (paths.length > 100) throw new Error(`too many entries: ${paths.length} (max 100)`);
1502
+ let command = "tar -czf -";
1503
+ for (const raw of paths) {
1504
+ const path = String(raw).replace(/\\/g, "/").replace(/\/+$/, "");
1505
+ if (path === "" || path === "/") throw new Error("refusing to archive the remote root");
1506
+ if (!path.startsWith("/")) throw new Error("remote path must be absolute");
1507
+ command += ` -C ${shQuote(posix.dirname(path))} ${shQuote(`./${posix.basename(path)}`)}`;
1508
+ }
1509
+ return command;
1510
+ }
1152
1511
  //#endregion
1153
1512
  //#region src/keygen.ts
1154
1513
  /**
@@ -1764,6 +2123,78 @@ function makeRoutes(deps) {
1764
2123
  const timeouts = () => deps.timeouts?.() ?? DEFAULT_TIMEOUTS;
1765
2124
  const files = new RemoteFiles(pool);
1766
2125
  const terminalSessions = new TerminalSessionRegistry(pool);
2126
+ /**
2127
+ * Stream one remote `tar -czf -` command into a `.tar.gz` download response.
2128
+ *
2129
+ * Shared by the directory and multi-selection routes (they differ only in the
2130
+ * command and the attachment name). The archive is produced remotely; the
2131
+ * response has no length, backpressure pauses the channel, and a non-zero tar
2132
+ * exit destroys the response with the stderr tail.
2133
+ */
2134
+ const streamArchive = async (alias, command, res, downloadName) => {
2135
+ let channel;
2136
+ try {
2137
+ channel = await pool.execChannel(alias, command);
2138
+ } catch (error) {
2139
+ writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) });
2140
+ return;
2141
+ }
2142
+ res.writeHead(200, {
2143
+ "content-type": "application/gzip",
2144
+ "content-disposition": attachmentHeader(downloadName),
2145
+ "cache-control": "no-store",
2146
+ "x-content-type-options": "nosniff"
2147
+ });
2148
+ let closed = false;
2149
+ /** `undefined` until the remote process reports one. */
2150
+ let exitCode;
2151
+ let stderr = "";
2152
+ /** Finish once: end on success, destroy on failure, close the remote channel either way. */
2153
+ const stop = (error) => {
2154
+ if (closed) return;
2155
+ closed = true;
2156
+ try {
2157
+ channel.close();
2158
+ } catch {}
2159
+ if (error === void 0) {
2160
+ try {
2161
+ res.end();
2162
+ } catch {}
2163
+ return;
2164
+ }
2165
+ res.destroy(error);
2166
+ };
2167
+ channel.stdout.on("data", (chunk) => {
2168
+ if (closed) return;
2169
+ try {
2170
+ if (!res.write(chunk)) channel.stdout.pause();
2171
+ } catch (error) {
2172
+ stop(error instanceof Error ? error : new Error(String(error)));
2173
+ }
2174
+ });
2175
+ res.on("drain", () => {
2176
+ if (!closed) try {
2177
+ channel.stdout.resume();
2178
+ } catch {}
2179
+ });
2180
+ channel.stderr.on("data", (chunk) => {
2181
+ if (stderr.length < 16384) stderr += chunk.toString("utf8");
2182
+ });
2183
+ channel.on("error", (error) => stop(error));
2184
+ channel.on("exit", (code) => {
2185
+ exitCode = code;
2186
+ });
2187
+ channel.on("close", () => {
2188
+ if (closed) return;
2189
+ if (exitCode !== 0) {
2190
+ const detail = stderr.trim() === "" ? "no stderr" : stderr.trim().slice(0, 400);
2191
+ stop(/* @__PURE__ */ new Error(`tar failed (${exitCode === null ? "signal" : exitCode}): ${detail}`));
2192
+ return;
2193
+ }
2194
+ stop();
2195
+ });
2196
+ res.on("close", () => stop());
2197
+ };
1767
2198
  /** Apply parsed import payloads; per-entry errors become skips. */
1768
2199
  const applyImport = (parsed) => {
1769
2200
  const imported = [];
@@ -2151,6 +2582,113 @@ function makeRoutes(deps) {
2151
2582
  }
2152
2583
  }
2153
2584
  },
2585
+ {
2586
+ kind: "exact",
2587
+ path: REMOTE_API.download,
2588
+ handler: async (req, res) => {
2589
+ if (!isLoopbackRequest(req)) {
2590
+ writeJson(res, 403, { error: "forbidden: loopback-only" });
2591
+ return;
2592
+ }
2593
+ if (req.method !== "GET") {
2594
+ writeJson(res, 405, { error: `method not allowed: ${req.method}` });
2595
+ return;
2596
+ }
2597
+ const url = new URL(req.url ?? "/", "http://localhost");
2598
+ const alias = url.searchParams.get("alias") ?? "";
2599
+ const path = url.searchParams.get("path") ?? "";
2600
+ if (alias === "" || path === "") {
2601
+ writeJson(res, 400, { error: "alias and path query parameters are required" });
2602
+ return;
2603
+ }
2604
+ if (!path.startsWith("/")) {
2605
+ writeJson(res, 400, { error: `path must be absolute: ${path}` });
2606
+ return;
2607
+ }
2608
+ try {
2609
+ await files.download(alias, path, res);
2610
+ } catch (error) {
2611
+ const message = error instanceof Error ? error.message : String(error);
2612
+ if (!res.headersSent && !res.destroyed) writeJson(res, 502, { error: message });
2613
+ else res.destroy(error instanceof Error ? error : void 0);
2614
+ }
2615
+ }
2616
+ },
2617
+ {
2618
+ kind: "exact",
2619
+ path: REMOTE_API.downloadDir,
2620
+ handler: async (req, res) => {
2621
+ if (!isLoopbackRequest(req)) {
2622
+ writeJson(res, 403, { error: "forbidden: loopback-only" });
2623
+ return;
2624
+ }
2625
+ if (req.method !== "GET") {
2626
+ writeJson(res, 405, { error: `method not allowed: ${req.method}` });
2627
+ return;
2628
+ }
2629
+ const url = new URL(req.url ?? "/", "http://localhost");
2630
+ const alias = url.searchParams.get("alias") ?? "";
2631
+ const path = url.searchParams.get("path") ?? "";
2632
+ if (alias === "" || path === "") {
2633
+ writeJson(res, 400, { error: "alias and path query parameters are required" });
2634
+ return;
2635
+ }
2636
+ if (!path.startsWith("/")) {
2637
+ writeJson(res, 400, { error: `path must be absolute: ${path}` });
2638
+ return;
2639
+ }
2640
+ let command;
2641
+ try {
2642
+ if (!(await files.stat(alias, path)).isDir) {
2643
+ writeJson(res, 400, { error: `not a directory: ${path}` });
2644
+ return;
2645
+ }
2646
+ command = directoryArchiveCommand(path);
2647
+ } catch (error) {
2648
+ writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) });
2649
+ return;
2650
+ }
2651
+ await streamArchive(alias, command, res, directoryArchiveName(path));
2652
+ }
2653
+ },
2654
+ {
2655
+ kind: "exact",
2656
+ path: REMOTE_API.downloadMany,
2657
+ handler: async (req, res) => {
2658
+ if (!isLoopbackRequest(req)) {
2659
+ writeJson(res, 403, { error: "forbidden: loopback-only" });
2660
+ return;
2661
+ }
2662
+ if (req.method !== "GET") {
2663
+ writeJson(res, 405, { error: `method not allowed: ${req.method}` });
2664
+ return;
2665
+ }
2666
+ const url = new URL(req.url ?? "/", "http://localhost");
2667
+ const alias = url.searchParams.get("alias") ?? "";
2668
+ const paths = url.searchParams.getAll("path");
2669
+ if (alias === "" || paths.length === 0) {
2670
+ writeJson(res, 400, { error: "alias and at least one path query parameter are required" });
2671
+ return;
2672
+ }
2673
+ if (paths.length > 100) {
2674
+ writeJson(res, 400, { error: `too many entries: ${paths.length} (max 100)` });
2675
+ return;
2676
+ }
2677
+ for (const path of paths) if (!path.startsWith("/")) {
2678
+ writeJson(res, 400, { error: `path must be absolute: ${path}` });
2679
+ return;
2680
+ }
2681
+ let command;
2682
+ try {
2683
+ for (const path of paths) await files.stat(alias, path);
2684
+ command = selectionArchiveCommand(paths);
2685
+ } catch (error) {
2686
+ writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) });
2687
+ return;
2688
+ }
2689
+ await streamArchive(alias, command, res, selectionDownloadName(paths.length));
2690
+ }
2691
+ },
2154
2692
  {
2155
2693
  kind: "exact",
2156
2694
  path: REMOTE_API.workspaces,
@@ -1,4 +1,4 @@
1
- import { l as aliasRoot, n as isWindowsAbsolute } from "./worlds-a8nqW9mi.js";
1
+ import { n as isWindowsAbsolute, u as aliasRoot } from "./worlds-C6Xha1mQ.js";
2
2
  import { FileSystem, FsError } from "@deepseek-ai/dsh-fs";
3
3
  //#region src/p2/router-fs.ts
4
4
  /**
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Remote directory archiving for the download route.
3
+ *
4
+ * The archive is produced ON the remote host (`tar -czf -`) and streamed
5
+ * straight into the HTTP response, so the Host never builds it in memory or
6
+ * writes it to its own disk. Pure string builders (no fs, no exec) so the
7
+ * download gate can pin the exact command shape.
8
+ */
9
+ /** Download file name for one archived directory. */
10
+ export declare function directoryArchiveName(dir: string): string;
11
+ /**
12
+ * One POSIX shell command that writes the directory's gzip tar to stdout.
13
+ *
14
+ * The member name is prefixed with `./` so a directory whose name starts with
15
+ * `-` cannot be read as a tar option; `-C` names the parent instead of relying
16
+ * on a shell `cd`, and both paths are single-quoted (`shQuote`) so spaces,
17
+ * quotes and `$()` in a real path cannot escape into the command.
18
+ */
19
+ export declare function directoryArchiveCommand(dir: string): string;
20
+ /**
21
+ * One POSIX shell command archiving several selected paths to stdout.
22
+ *
23
+ * GNU tar accepts one `-C` before each member, so every entry is stored as its
24
+ * own bare `./name` while keeping its real parent on the remote side; that is
25
+ * what lets a selection span several directories (mixed files and directories
26
+ * are fine — tar recurses into directories). Two entries with the same basename
27
+ * from different directories collide inside the archive by design: the
28
+ * alternative would be a synthetic directory tree the remote never had.
29
+ */
30
+ export declare function selectionArchiveCommand(paths: readonly string[]): string;