dsh-remote-vs 0.13.0 → 0.15.1

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.
Files changed (128) hide show
  1. package/README.en.md +455 -443
  2. package/README.md +408 -396
  3. package/lib/client.js +8062 -2651
  4. package/lib/index.js +1058 -288
  5. package/lib/p2-router-fs.js +1 -1
  6. package/lib/p2-router-refs.js +89 -10
  7. package/lib/p2-router-spill.js +73 -1
  8. package/lib/p2-router-subprocess.js +18 -6
  9. package/lib/spill-retention-BwKEWrl5.js +115 -0
  10. package/lib/{ssh-proc-arI5lm4W.js → ssh-proc-VKWn_LZC.js} +17 -0
  11. package/lib/types/archive.d.ts +1 -1
  12. package/lib/types/changes/recorder.d.ts +34 -2
  13. package/lib/types/client/CodeEditor.d.ts +12 -0
  14. package/lib/types/client/ConnectionStatus.d.ts +17 -0
  15. package/lib/types/client/DirectoryFlow.d.ts +2 -0
  16. package/lib/types/client/DoctorPanel.d.ts +25 -0
  17. package/lib/types/client/QuickOpen.d.ts +17 -0
  18. package/lib/types/client/RemoteExplorer.d.ts +192 -1
  19. package/lib/types/client/RemoteRoot.d.ts +17 -0
  20. package/lib/types/client/SearchView.d.ts +55 -0
  21. package/lib/types/client/TerminalView.d.ts +38 -0
  22. package/lib/types/client/WorkspaceWizard.d.ts +17 -0
  23. package/lib/types/client/api.d.ts +54 -4
  24. package/lib/types/client/changes/undo-affordance.d.ts +16 -0
  25. package/lib/types/client/changes/undo-context.d.ts +14 -18
  26. package/lib/types/client/changes/undo-target.d.ts +78 -0
  27. package/lib/types/client/connection.d.ts +111 -0
  28. package/lib/types/client/doctor.d.ts +122 -0
  29. package/lib/types/client/download.d.ts +35 -5
  30. package/lib/types/client/downloads.d.ts +18 -1
  31. package/lib/types/client/file-open-probe.d.ts +64 -0
  32. package/lib/types/client/i18n.d.ts +1 -1
  33. package/lib/types/client/quickopen-model.d.ts +332 -0
  34. package/lib/types/client/scm/DiffView.d.ts +34 -0
  35. package/lib/types/client/scm/actions.d.ts +18 -0
  36. package/lib/types/client/scm/diff-model.d.ts +17 -1
  37. package/lib/types/client/scm/git-cache.d.ts +10 -2
  38. package/lib/types/client/scm/read-queue.d.ts +2 -1
  39. package/lib/types/client/scm/stage-queue.d.ts +13 -0
  40. package/lib/types/client/scm/status-map.d.ts +3 -1
  41. package/lib/types/client/store.d.ts +114 -5
  42. package/lib/types/client/vsc/FindWidget.d.ts +7 -0
  43. package/lib/types/client/vsc/save-shortcut.d.ts +57 -0
  44. package/lib/types/deploy.d.ts +44 -2
  45. package/lib/types/git-format.d.ts +15 -0
  46. package/lib/types/http.d.ts +44 -0
  47. package/lib/types/p2/file-refs.d.ts +39 -2
  48. package/lib/types/p2/helper-rpc.d.ts +26 -0
  49. package/lib/types/p2/router-spill.d.ts +19 -0
  50. package/lib/types/p2/router-subprocess.d.ts +2 -0
  51. package/lib/types/p2/spill-retention.d.ts +74 -0
  52. package/lib/types/p2/worlds.d.ts +11 -0
  53. package/lib/types/pool.d.ts +73 -11
  54. package/lib/types/protocol.d.ts +63 -0
  55. package/lib/types/routes.d.ts +18 -0
  56. package/lib/types/sftp.d.ts +114 -8
  57. package/lib/types/store.d.ts +34 -0
  58. package/lib/types/timeouts.d.ts +14 -0
  59. package/lib/{worlds-C6Xha1mQ.js → worlds-Be1YE2Ot.js} +727 -78
  60. package/package.json +1 -1
  61. package/src/archive.ts +41 -9
  62. package/src/changes/recorder.ts +227 -31
  63. package/src/changes/status.ts +37 -1
  64. package/src/client/CodeEditor.tsx +84 -2
  65. package/src/client/ConnectionStatus.tsx +130 -0
  66. package/src/client/DirectoryFlow.tsx +40 -5
  67. package/src/client/DoctorPanel.tsx +202 -0
  68. package/src/client/DownloadDock.tsx +13 -25
  69. package/src/client/EditorPane.tsx +291 -7
  70. package/src/client/HostsView.tsx +17 -8
  71. package/src/client/QuickOpen.tsx +371 -0
  72. package/src/client/RemoteDirectoryPicker.tsx +54 -3
  73. package/src/client/RemoteExplorer.tsx +879 -160
  74. package/src/client/RemoteRoot.tsx +178 -1
  75. package/src/client/SearchView.tsx +180 -6
  76. package/src/client/SettingsHosts.tsx +1 -1
  77. package/src/client/TerminalView.tsx +174 -9
  78. package/src/client/WorkspaceWizard.tsx +110 -16
  79. package/src/client/WorkspacesView.tsx +22 -6
  80. package/src/client/api.ts +197 -11
  81. package/src/client/changes/ChangesDock.tsx +35 -8
  82. package/src/client/changes/undo-affordance.ts +33 -0
  83. package/src/client/changes/undo-context.ts +14 -18
  84. package/src/client/changes/undo-target.ts +139 -0
  85. package/src/client/connection.ts +264 -0
  86. package/src/client/doctor.ts +441 -0
  87. package/src/client/download.ts +148 -12
  88. package/src/client/downloads.ts +43 -2
  89. package/src/client/file-open-probe.ts +83 -0
  90. package/src/client/i18n.ts +244 -0
  91. package/src/client/index.tsx +5 -2
  92. package/src/client/quickopen-model.ts +778 -0
  93. package/src/client/remote-file-open.ts +21 -33
  94. package/src/client/scm/DiffView.tsx +116 -6
  95. package/src/client/scm/ScmPanel.tsx +19 -0
  96. package/src/client/scm/actions.ts +34 -2
  97. package/src/client/scm/diff-model.ts +33 -37
  98. package/src/client/scm/git-cache.ts +61 -4
  99. package/src/client/scm/read-queue.ts +33 -2
  100. package/src/client/scm/stage-queue.ts +72 -1
  101. package/src/client/scm/status-map.ts +22 -1
  102. package/src/client/store.tsx +704 -21
  103. package/src/client/vsc/FindWidget.tsx +20 -0
  104. package/src/client/vsc/kit.tsx +115 -6
  105. package/src/client/vsc/reveal-line.ts +33 -14
  106. package/src/client/vsc/save-shortcut.ts +131 -0
  107. package/src/client/vsc/vsc.css +419 -0
  108. package/src/deploy.ts +185 -33
  109. package/src/git-format.ts +136 -22
  110. package/src/git-ops.ts +14 -6
  111. package/src/http.ts +80 -12
  112. package/src/importers.ts +80 -21
  113. package/src/index.ts +21 -1
  114. package/src/p2/file-refs.ts +112 -10
  115. package/src/p2/helper-rpc.ts +73 -36
  116. package/src/p2/router-spill.ts +96 -1
  117. package/src/p2/router-subprocess.ts +18 -5
  118. package/src/p2/spill-retention.ts +134 -0
  119. package/src/p2/ssh-proc.ts +22 -0
  120. package/src/p2/worlds.ts +24 -0
  121. package/src/pool.ts +329 -47
  122. package/src/protocol.ts +66 -0
  123. package/src/routes.ts +251 -43
  124. package/src/sftp.ts +486 -26
  125. package/src/store.ts +207 -85
  126. package/src/terminal.ts +38 -2
  127. package/src/timeouts.ts +14 -0
  128. package/src/tools.ts +14 -5
@@ -1,6 +1,7 @@
1
- import { t as SshProcRuntime } from "./ssh-proc-arI5lm4W.js";
1
+ import { t as SshProcRuntime } from "./ssh-proc-VKWn_LZC.js";
2
+ import { i as spillSweepCommand, r as spillDirSweepCommand } from "./spill-retention-BwKEWrl5.js";
2
3
  import { createRequire } from "node:module";
3
- import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync } from "node:fs";
4
+ import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync } from "node:fs";
4
5
  import { createHash, randomBytes } from "node:crypto";
5
6
  import path, { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
6
7
  import { homedir } from "node:os";
@@ -16860,6 +16861,79 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports, module) => {
16860
16861
  };
16861
16862
  }));
16862
16863
  //#endregion
16864
+ //#region src/timeouts.ts
16865
+ /**
16866
+ * An operation that ran out of its wall-clock budget.
16867
+ *
16868
+ * Tagged on purpose: callers have to tell "the remote never answered" from a real
16869
+ * remote failure (a missing path must not cost the session), and matching on the
16870
+ * message text would silently stop working the moment the template changed.
16871
+ *
16872
+ * It lives in this module because "a budget ran out" is a timeout fact, not a
16873
+ * pool or an SFTP fact: both halves need the same type to keep the distinction
16874
+ * (the Host decides not to paint the link red, and the client must not downgrade
16875
+ * the editor to read-only for it).
16876
+ */
16877
+ var DeadlineError = class extends Error {};
16878
+ /** Smallest accepted timeout: below this, local work would start failing. */
16879
+ const MIN_TIMEOUT_MS = 1e3;
16880
+ /**
16881
+ * Largest accepted timeout — the exec route clamps to the same ceiling.
16882
+ *
16883
+ * Raised from 10 to 30 minutes when the SCM push gained a live output panel:
16884
+ * a Gerrit push on a large repo waits for server-side hooks and can outlast
16885
+ * the old ceiling with nothing wrong on either side.
16886
+ */
16887
+ const MAX_TIMEOUT_MS = 18e5;
16888
+ /**
16889
+ * Default for one git command (status/log/branches/diff over exec).
16890
+ *
16891
+ * 120 s was the old internal value and 45 s the old client deadline; both were
16892
+ * routinely exceeded by a cold `git status` on a large monorepo. Five minutes
16893
+ * still fails eventually (a wedged host must not spin forever) but outlasts any
16894
+ * plausible cold index walk.
16895
+ */
16896
+ const DEFAULT_GIT_TIMEOUT_MS = 3e5;
16897
+ /** Default for one SFTP file read (editor, diff sides, document preview). */
16898
+ const DEFAULT_READ_TIMEOUT_MS = 12e4;
16899
+ /** The pair every half starts from before any Host answer arrives. */
16900
+ const DEFAULT_TIMEOUTS = {
16901
+ gitMs: DEFAULT_GIT_TIMEOUT_MS,
16902
+ readMs: DEFAULT_READ_TIMEOUT_MS
16903
+ };
16904
+ /**
16905
+ * Clamp one untrusted timeout into the accepted range.
16906
+ *
16907
+ * @param value - raw value (plugin config, JSON body, anything).
16908
+ * @param fallback - used when the value is not a usable number.
16909
+ * @returns a whole number of milliseconds within [MIN, MAX].
16910
+ */
16911
+ function clampTimeout(value, fallback) {
16912
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
16913
+ const whole = Math.floor(value);
16914
+ if (whole < 1e3) return MIN_TIMEOUT_MS;
16915
+ if (whole > 18e5) return MAX_TIMEOUT_MS;
16916
+ return whole;
16917
+ }
16918
+ /**
16919
+ * Clamp an optional request timeout: absent/invalid stays absent, which is what
16920
+ * the exec route forwards as "use the pool default".
16921
+ *
16922
+ * @param value - raw `timeoutMs` from a request body.
16923
+ * @returns the clamped timeout, or undefined when the caller named none.
16924
+ */
16925
+ function clampExecTimeout(value) {
16926
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
16927
+ return clampTimeout(value, DEFAULT_GIT_TIMEOUT_MS);
16928
+ }
16929
+ /** Resolve the effective pair from raw config values. */
16930
+ function resolveTimeouts(config) {
16931
+ return {
16932
+ gitMs: clampTimeout(config?.gitTimeoutMs, DEFAULT_GIT_TIMEOUT_MS),
16933
+ readMs: clampTimeout(config?.readTimeoutMs, DEFAULT_READ_TIMEOUT_MS)
16934
+ };
16935
+ }
16936
+ //#endregion
16863
16937
  //#region src/sftp.ts
16864
16938
  /**
16865
16939
  * Remote file operations over SFTP. Paths are absolute POSIX paths on the
@@ -16879,6 +16953,35 @@ const LIST_ENTRY_CAP = 2e4;
16879
16953
  /** Largest single upload accepted (matches the client-side planner cap). */
16880
16954
  const UPLOAD_MAX_BYTES = 2 * 1024 * 1024 * 1024;
16881
16955
  /**
16956
+ * The remote file changed after the bytes the caller saved against were read.
16957
+ *
16958
+ * Carries what is there NOW so the route can answer 409 with the current
16959
+ * version instead of a bare message — the client shows "changed at …, N bytes"
16960
+ * and offers overwrite / reload / see-the-difference without a second round
16961
+ * trip. A missing target is a conflict too (`mtime`/`size` null): the file this
16962
+ * buffer was loaded from is gone, so writing would recreate something a person
16963
+ * or another tool deliberately removed.
16964
+ *
16965
+ * The mtime comparison is SFTP's own (second granularity), so this narrows the
16966
+ * window rather than closing it: two writes to the same inode inside one second
16967
+ * share an mtime. `expectSize` covers the common "same second, different
16968
+ * length" case and nothing more. It is a guard against silent loss, not a
16969
+ * strong consistency protocol — the docs say so.
16970
+ */
16971
+ var WriteConflictError = class extends Error {
16972
+ path;
16973
+ conflict;
16974
+ constructor(path, mtime, size) {
16975
+ super(`remote file changed since it was opened: ${path}`);
16976
+ this.path = path;
16977
+ this.name = "WriteConflictError";
16978
+ this.conflict = {
16979
+ mtime,
16980
+ size
16981
+ };
16982
+ }
16983
+ };
16984
+ /**
16882
16985
  * How long one download stream may make no progress before it is failed.
16883
16986
  *
16884
16987
  * A download has no wall-clock budget for the same reason an upload does not: a
@@ -16937,6 +17040,21 @@ const HANDLE_CLOSE_TIMEOUT_MS = 2e3;
16937
17040
  * the code did before them.
16938
17041
  */
16939
17042
  const MEMO_CAP = 512;
17043
+ /**
17044
+ * Fixed segment every side file this plugin creates carries.
17045
+ *
17046
+ * A sweep must never be able to name a file the user owns. Without a reserved
17047
+ * segment, the old shape (`.part-<8 hex>`) also matched a user's own
17048
+ * `foo.part-deadbeef`, and the age bound was the only thing between that file
17049
+ * and an irreversible delete. The segment makes "this name is shaped like ours"
17050
+ * checkable, and the per-process ownership registry below makes the delete
17051
+ * provable instead of guessed.
17052
+ */
17053
+ const PART_MARKER = ".dsh-rvs.part-";
17054
+ /** Side files one sweep removes at most, so a burst cannot become a long list. */
17055
+ const PART_SWEEP_MAX_PER_DIR = 50;
17056
+ /** Side-file name shape shared by `write` and `upload` (marker + 8 hex). */
17057
+ const PART_NAME_RE = /\.dsh-rvs\.part-[0-9a-f]{8}$/;
16940
17058
  /** SFTP status code for "no such file or directory" (ssh2 sets `error.code`). */
16941
17059
  const SFTP_NO_SUCH_FILE = 2;
16942
17060
  /** Generic SFTP failure — what OpenSSH returns for most non-ENOENT errors. */
@@ -16956,11 +17074,13 @@ function remotePath(path) {
16956
17074
  *
16957
17075
  * The download's one-shot calls (`lstat`, `open`, `fstat`, an extra channel's
16958
17076
  * handle) have no progress signal, so this is the only thing between a stalled
16959
- * server and a response — and two SFTP channels — pinned forever.
17077
+ * server and a response — and two SFTP channels — pinned forever. The rejection
17078
+ * is a `DeadlineError`, not a plain error: a budget that ran out must not be
17079
+ * reported to the status chip as a dead link (see `pool.noteOpFailure`).
16960
17080
  */
16961
17081
  function bounded(promise, ms, message) {
16962
17082
  return new Promise((resolve, reject) => {
16963
- const timer = setTimeout(() => reject(new Error(message)), ms);
17083
+ const timer = setTimeout(() => reject(new DeadlineError(message)), ms);
16964
17084
  timer.unref?.();
16965
17085
  promise.then((value) => {
16966
17086
  clearTimeout(timer);
@@ -16992,6 +17112,24 @@ var RemoteFiles = class {
16992
17112
  knownDirs = /* @__PURE__ */ new Set();
16993
17113
  /** Listings already reported as truncated; the log line stays one per path. */
16994
17114
  capWarned = /* @__PURE__ */ new Set();
17115
+ /**
17116
+ * Side files this process is still writing (`alias\0path`). A sweep skips them
17117
+ * regardless of age — they are not orphans.
17118
+ */
17119
+ activePartials = /* @__PURE__ */ new Set();
17120
+ /**
17121
+ * Side files this process CREATED and could not remove (`alias\0path`).
17122
+ *
17123
+ * This is the ONLY set a sweep may delete from. Deleting a name that merely
17124
+ * LOOKS like a side file is a guess, and guessing wrong destroys the user's
17125
+ * data (the audit's P2-N1: `foo.part-deadbeef` in a directory that once
17126
+ * recorded an orphan, older than the age bound, was irreversibly removed).
17127
+ * A leftover from a previous Host process is therefore never swept either:
17128
+ * junk that stays is recoverable, a deleted user file is not.
17129
+ */
17130
+ ownedPartials = /* @__PURE__ */ new Set();
17131
+ /** alias -> directories that may hold an owned side file (sweep on next write). */
17132
+ orphanDirs = /* @__PURE__ */ new Map();
16995
17133
  constructor(pool) {
16996
17134
  this.pool = pool;
16997
17135
  }
@@ -17026,42 +17164,126 @@ var RemoteFiles = class {
17026
17164
  async read(alias, file) {
17027
17165
  const path = remotePath(file);
17028
17166
  return this.pool.withBrowseSftp(alias, async (sftp) => {
17029
- const attrs = await lstatAsync(sftp, path).catch(async (error) => {
17167
+ /**
17168
+ * Resolve to the REAL file first, exactly the way `write` does.
17169
+ *
17170
+ * A bare `lstat` describes a SYMBOLIC LINK (its own mtime, and the link
17171
+ * target string's length as the size) while the bytes read through the path
17172
+ * come from the target — so the mtime/size pair the editor stores as its
17173
+ * save baseline described a different thing than the save would compare,
17174
+ * and the first save of every symlinked file conflicted with itself
17175
+ * forever (reloading re-read the link's mtime again). Resolving here makes
17176
+ * read and write agree on which version they are talking about; the link
17177
+ * itself is untouched, which is what "writes through symlinks" means.
17178
+ */
17179
+ const target = await resolveWriteTarget(sftp, path).catch(async (error) => {
17030
17180
  throw await explainSftpFailure(sftp, path, "file", error) ?? error;
17031
17181
  });
17032
- if (isDir(attrs.mode)) throw new Error(`not a file: ${path} is a directory`);
17033
- const size = attrs.size;
17182
+ if (target.size === void 0 || target.mtime === void 0) throw new Error(`no such file: ${path}`);
17183
+ const size = target.size;
17034
17184
  if (size <= 0) return {
17035
17185
  size: 0,
17186
+ mtime: target.mtime,
17036
17187
  binary: false,
17037
17188
  text: "",
17038
17189
  truncated: false
17039
17190
  };
17040
- const buffer = await readWindow(sftp, path, 0, Math.min(size, READ_CAP));
17191
+ const window = Math.min(size, READ_CAP);
17192
+ const buffer = await readWindow(sftp, target.realPath, 0, window);
17041
17193
  const binary = buffer.includes(0);
17042
17194
  return {
17043
17195
  size,
17196
+ mtime: target.mtime,
17044
17197
  binary,
17045
17198
  ...binary ? { base64: buffer.toString("base64") } : { text: buffer.toString("utf8") },
17046
17199
  truncated: size > READ_CAP
17047
17200
  };
17048
17201
  });
17049
17202
  }
17050
- async write(alias, file, content, encoding = "utf8") {
17203
+ /**
17204
+ * Write one file whole (the remote editor's save / `remote_write`), atomically.
17205
+ *
17206
+ * Not `writeFile` on the target: that truncates it first, so an interrupted
17207
+ * save (a dropped link, a Host restart, a full disk mid-write) left the
17208
+ * previous content gone AND the new one half written. The bytes go to a SIDE
17209
+ * file next to the target (`.dsh-rvs.part-<8 hex>`, see `PART_MARKER`) and are
17210
+ * only moved into place once the body is complete.
17211
+ *
17212
+ * "Moved into place" must not delete the target first: the old unlink-then-
17213
+ * rename pair had a window where a failed rename left NEITHER the old file nor
17214
+ * the new one, and reported it as `no such file`. `replaceFile` therefore uses
17215
+ * OpenSSH's atomic `posix-rename` when the server advertises it, and otherwise
17216
+ * swaps the target aside with a rollback, so the previous bytes survive every
17217
+ * failure with the real error attached.
17218
+ *
17219
+ * Two things a fresh inode would otherwise lose:
17220
+ * - a symbolic link target: the side file lives next to the link's REAL
17221
+ * target and the link itself is left alone (the old in-place write punched
17222
+ * through it; replacing it with a plain file silently changed what the path
17223
+ * means);
17224
+ * - the permission bits: they are copied back with `setstat` after the swap.
17225
+ * Owner/group cannot be preserved without a privileged chown, so a save
17226
+ * keeps the bytes and the mode but takes the SSH user's ownership.
17227
+ */
17228
+ async write(alias, file, content, encoding = "utf8", guard) {
17051
17229
  const path = remotePath(file);
17052
- const dir = posix.dirname(path);
17053
17230
  const data = encoding === "base64" ? Buffer.from(content, "base64") : Buffer.from(content, "utf8");
17054
17231
  return this.pool.withSftp(alias, async (sftp) => {
17232
+ /** Set once the target may be mid-swap: such failures are never reworded. */
17233
+ let replacing = false;
17234
+ let partial;
17235
+ /** The new version's mtime; null when it could not be read back. */
17236
+ let mtime = null;
17237
+ /** The new version's size, from the same stat as `mtime` when possible. */
17238
+ let writtenSize = data.length;
17055
17239
  try {
17240
+ const target = await resolveWriteTarget(sftp, path);
17241
+ /**
17242
+ * The optimistic lock, checked against the SAME stat that resolved the
17243
+ * target — before a side file is even named, so a refused save touches
17244
+ * nothing at all.
17245
+ *
17246
+ * A missing target conflicts when the caller HAD a baseline: the file
17247
+ * these bytes were loaded from is gone (a terminal `rm`, an agent's
17248
+ * rename), and writing would silently resurrect it. Without a baseline
17249
+ * the caller is creating the file and has nothing to compare.
17250
+ */
17251
+ if (guard !== void 0 && guard.expectMtime !== void 0) {
17252
+ if (target.mtime === void 0 || target.mtime !== guard.expectMtime || guard.expectSize !== void 0 && target.size !== guard.expectSize) throw new WriteConflictError(target.realPath, target.mtime ?? null, target.size ?? null);
17253
+ }
17254
+ const dir = posix.dirname(target.realPath);
17255
+ partial = partialPathOf(target.realPath);
17256
+ this.trackPartial(alias, partial);
17056
17257
  await this.withDirRetry(alias, dir, async () => {
17057
17258
  await this.ensureDir(sftp, alias, dir);
17058
- if (data.length === 0) await touchFile(sftp, path);
17059
- else await writeFileAsync(sftp, path, data);
17259
+ if (data.length === 0) await touchFile(sftp, partial);
17260
+ else await writeFileAsync(sftp, partial, data);
17060
17261
  });
17262
+ replacing = true;
17263
+ await replaceFile(sftp, partial, target.realPath);
17264
+ this.forgetPartial(alias, partial);
17265
+ if (target.mode !== void 0) await setstatAsync(sftp, target.realPath, { mode: target.mode }).catch(() => {
17266
+ console.warn(`[dsh-remote-vs] saved ${target.realPath} but could not restore its mode`);
17267
+ });
17268
+ const after = await lstatAsync(sftp, target.realPath).catch(() => void 0);
17269
+ if (after !== void 0) {
17270
+ mtime = after.mtime * 1e3;
17271
+ writtenSize = after.size;
17272
+ }
17273
+ this.remember(this.knownDirs, dirKey(alias, posix.dirname(path)));
17274
+ await this.sweepOrphanDirs(sftp, alias, dir);
17061
17275
  } catch (error) {
17276
+ if (error instanceof WriteConflictError) throw error;
17277
+ if (partial !== void 0) await this.discardPartial(sftp, alias, partial);
17278
+ if (replacing) throw error;
17062
17279
  throw await explainSftpFailure(sftp, path, "file", error) ?? error;
17280
+ } finally {
17281
+ if (partial !== void 0) this.activePartials.delete(dirKey(alias, partial));
17063
17282
  }
17064
- return { size: data.length };
17283
+ return {
17284
+ size: writtenSize,
17285
+ mtime
17286
+ };
17065
17287
  });
17066
17288
  }
17067
17289
  /**
@@ -17073,12 +17295,13 @@ var RemoteFiles = class {
17073
17295
  * first — a drop can name a path several levels below the target — and the
17074
17296
  * source is piped straight into the SFTP write stream.
17075
17297
  *
17076
- * The bytes go to a SIDE file (`.part-<id>` next to the target) and are
17077
- * renamed into place only once the body ended cleanly. Writing the real path
17298
+ * The bytes go to a SIDE file (`.dsh-rvs.part-<8 hex>` next to the target) and
17299
+ * are renamed into place only once the body ended cleanly. Writing the real path
17078
17300
  * directly left a half file behind whenever the upload was cancelled, which
17079
17301
  * then looked like a complete file in the explorer (2026-10-20 user report).
17080
- * On any failure the side file is removed, so a cancelled upload leaves the
17081
- * remote folder exactly as it was.
17302
+ * A cancelled upload removes its side file; when the CONNECTION is what failed
17303
+ * the unlink cannot run, so the directory is recorded and the next successful
17304
+ * write into it sweeps the orphan (see `sweepOrphanDirs`).
17082
17305
  *
17083
17306
  * @param alias - host alias.
17084
17307
  * @param file - absolute remote destination path.
@@ -17090,20 +17313,25 @@ var RemoteFiles = class {
17090
17313
  async upload(alias, file, source, maxBytes = UPLOAD_MAX_BYTES, overwrite = true) {
17091
17314
  const path = remotePath(file);
17092
17315
  const dir = posix.dirname(path);
17093
- const partial = `${path}.part-${randomBytes(4).toString("hex")}`;
17316
+ const partial = partialPathOf(path);
17094
17317
  return this.pool.withSftp(alias, async (sftp) => {
17095
17318
  try {
17096
17319
  await this.withDirRetry(alias, dir, async () => {
17097
17320
  await this.ensureDir(sftp, alias, dir);
17098
17321
  });
17322
+ this.trackPartial(alias, partial);
17099
17323
  const size = await streamIntoFile(sftp, partial, source, maxBytes);
17100
17324
  if (overwrite) await unlinkAsync(sftp, path).catch(() => void 0);
17101
17325
  await renameAsync(sftp, partial, path);
17326
+ this.forgetPartial(alias, partial);
17102
17327
  this.remember(this.knownDirs, dirKey(alias, dir));
17328
+ await this.sweepOrphanDirs(sftp, alias, dir);
17103
17329
  return { size };
17104
17330
  } catch (error) {
17105
- await unlinkAsync(sftp, partial).catch(() => void 0);
17331
+ await this.discardPartial(sftp, alias, partial);
17106
17332
  throw await explainSftpFailure(sftp, path, "file", error) ?? error;
17333
+ } finally {
17334
+ this.activePartials.delete(dirKey(alias, partial));
17107
17335
  }
17108
17336
  }, { timeoutMs: 0 });
17109
17337
  }
@@ -17167,7 +17395,7 @@ var RemoteFiles = class {
17167
17395
  }
17168
17396
  await pipeChannelsToResponse(channels, attrs.size, res);
17169
17397
  } finally {
17170
- for (const channel of channels) await closeQuietly(channel.sftp, channel.handle);
17398
+ for (const channel of channels) await closeQuietly$1(channel.sftp, channel.handle);
17171
17399
  }
17172
17400
  });
17173
17401
  }
@@ -17262,6 +17490,101 @@ var RemoteFiles = class {
17262
17490
  return await op();
17263
17491
  }
17264
17492
  }
17493
+ /**
17494
+ * Remove a side file, remembering its directory when that is impossible.
17495
+ *
17496
+ * The only failure that leaves a side file behind is the failure it was
17497
+ * cleaning up after: with the connection dead, `unlink` cannot run either.
17498
+ * Recording the directory lets the NEXT successful write into it sweep the
17499
+ * orphan — otherwise it stays in the remote directory forever, looking like a
17500
+ * file the user created.
17501
+ */
17502
+ async discardPartial(sftp, alias, partial) {
17503
+ try {
17504
+ await unlinkAsync(sftp, partial);
17505
+ this.forgetPartial(alias, partial);
17506
+ } catch {
17507
+ this.rememberOwned(dirKey(alias, partial));
17508
+ this.markOrphanDir(alias, posix.dirname(partial));
17509
+ }
17510
+ }
17511
+ /** Register one side file as ours: in flight now, and sweepable after it fails. */
17512
+ trackPartial(alias, partial) {
17513
+ this.activePartials.add(dirKey(alias, partial));
17514
+ this.rememberOwned(dirKey(alias, partial));
17515
+ }
17516
+ /** Add one owned side-file key, evicting the oldest when the set is full. */
17517
+ rememberOwned(key) {
17518
+ if (!this.ownedPartials.has(key) && this.ownedPartials.size >= MEMO_CAP) {
17519
+ const oldest = this.ownedPartials.values().next().value;
17520
+ if (oldest !== void 0) this.ownedPartials.delete(oldest);
17521
+ }
17522
+ this.ownedPartials.add(key);
17523
+ }
17524
+ /** The side file reached its target (or was removed): no longer ours to sweep. */
17525
+ forgetPartial(alias, partial) {
17526
+ this.ownedPartials.delete(dirKey(alias, partial));
17527
+ }
17528
+ markOrphanDir(alias, dir) {
17529
+ const dirs = this.orphanDirs.get(alias) ?? /* @__PURE__ */ new Set();
17530
+ if (dirs.size >= MEMO_CAP) return;
17531
+ dirs.add(dir);
17532
+ this.orphanDirs.set(alias, dirs);
17533
+ }
17534
+ /**
17535
+ * Remove the side files THIS process left behind in `dir`.
17536
+ *
17537
+ * Runs after a SUCCESSFUL write/upload into a directory that recorded an
17538
+ * orphan, so the healthy path pays nothing. Two independent locks keep it off
17539
+ * anything the user owns:
17540
+ *
17541
+ * 1. the name must match the plugin's reserved shape (`.dsh-rvs.part-<8 hex>`);
17542
+ * 2. the exact path must be in `ownedPartials` — a set only `trackPartial`
17543
+ * writes, i.e. a file this process itself created.
17544
+ *
17545
+ * The shape alone would still be a guess (the audit's P2-N1: a user file
17546
+ * `foo.part-deadbeef` was deleted after the age bound), so the ownership check
17547
+ * is the load-bearing one. A leftover from a PREVIOUS Host process carries the
17548
+ * shape but is not owned, and is therefore never deleted either — including a
17549
+ * side file left by a pre-marker release (`.part-<8 hex>`, which does not even
17550
+ * match the current shape). Junk that stays is recoverable; a deleted user
17551
+ * file is not.
17552
+ *
17553
+ * A sweep failure is never the caller's problem: the record simply survives
17554
+ * for the next write.
17555
+ */
17556
+ async sweepOrphanDirs(sftp, alias, dir) {
17557
+ const dirs = this.orphanDirs.get(alias);
17558
+ if (dirs === void 0 || !dirs.has(dir)) return;
17559
+ let rows;
17560
+ try {
17561
+ rows = await readdirAsync(sftp, dir);
17562
+ } catch {
17563
+ return;
17564
+ }
17565
+ let swept = 0;
17566
+ let failed = false;
17567
+ for (const row of rows) {
17568
+ if (!PART_NAME_RE.test(row.filename)) continue;
17569
+ const path = posix.join(dir, row.filename);
17570
+ const key = dirKey(alias, path);
17571
+ if (!this.ownedPartials.has(key)) continue;
17572
+ if (this.activePartials.has(key)) continue;
17573
+ if (swept >= PART_SWEEP_MAX_PER_DIR) {
17574
+ failed = true;
17575
+ break;
17576
+ }
17577
+ try {
17578
+ await unlinkAsync(sftp, path);
17579
+ this.ownedPartials.delete(key);
17580
+ swept += 1;
17581
+ } catch {
17582
+ failed = true;
17583
+ }
17584
+ }
17585
+ if (!failed) dirs.delete(dir);
17586
+ if (dirs.size === 0) this.orphanDirs.delete(alias);
17587
+ }
17265
17588
  /** Add one key to a bounded set, evicting the oldest entry when full. */
17266
17589
  remember(memo, key) {
17267
17590
  if (memo.size >= MEMO_CAP) {
@@ -17286,6 +17609,16 @@ var RemoteFiles = class {
17286
17609
  function dirKey(alias, path) {
17287
17610
  return `${alias}\u0000${path}`;
17288
17611
  }
17612
+ /**
17613
+ * Name of the side file a save/upload of `path` writes through.
17614
+ *
17615
+ * The reserved segment is what makes the name recognisably the plugin's (see
17616
+ * `PART_MARKER`); the 4 random bytes keep two concurrent operations on one
17617
+ * target apart.
17618
+ */
17619
+ function partialPathOf(path) {
17620
+ return `${path}${PART_MARKER}${randomBytes(4).toString("hex")}`;
17621
+ }
17289
17622
  function isSymlink(mode) {
17290
17623
  return (mode & S_IFMT) === S_IFLNK;
17291
17624
  }
@@ -17417,7 +17750,10 @@ async function readHandleFully(sftp, handle, buffer, position) {
17417
17750
  * (`index % channels.length`) so the in-flight bytes are spread across the SSH
17418
17751
  * channel windows instead of queueing behind one 2 MiB window. A closed response
17419
17752
  * (user cancel) resolves quietly — the route treats that as a cancellation, not
17420
- * an error — and a no-progress watchdog fails a silently dead transfer.
17753
+ * an error — and a no-progress watchdog fails a silently dead transfer. Every
17754
+ * suspension point (slot, chunk, and the writer's `drain` wait) is released by
17755
+ * that close as well, so the caller's `finally` — handles, sessions, slots —
17756
+ * always runs.
17421
17757
  */
17422
17758
  async function pipeChannelsToResponse(channels, size, res) {
17423
17759
  const chunkBytes = TRANSFER_CHUNK_BYTES;
@@ -17426,6 +17762,7 @@ async function pipeChannelsToResponse(channels, size, res) {
17426
17762
  const ready = /* @__PURE__ */ new Map();
17427
17763
  const chunkWaiters = /* @__PURE__ */ new Map();
17428
17764
  const slotWaiters = [];
17765
+ const drainWaiters = [];
17429
17766
  let slots = windowChunks;
17430
17767
  let nextRead = 0;
17431
17768
  let cancelled = false;
@@ -17438,6 +17775,18 @@ async function pipeChannelsToResponse(channels, size, res) {
17438
17775
  for (const wake of chunkWaiters.values()) wake();
17439
17776
  chunkWaiters.clear();
17440
17777
  };
17778
+ /**
17779
+ * Wake the ordered writer when the response ends underneath it.
17780
+ *
17781
+ * A destroyed response never emits `drain` again, so a `waitDrain()` that only
17782
+ * listens for `drain` would park the writer forever — and with it the
17783
+ * `finally` that closes the handles, the sessions and the pool's channel slots
17784
+ * (a cancelled download used to leak both channels until the Host restarted).
17785
+ * `close` and a transfer-level failure therefore have to release the same wait.
17786
+ */
17787
+ const wakeDrain = () => {
17788
+ for (const wake of drainWaiters.splice(0)) wake();
17789
+ };
17441
17790
  const signalChunk = (index) => {
17442
17791
  const wake = chunkWaiters.get(index);
17443
17792
  if (wake !== void 0) {
@@ -17450,6 +17799,7 @@ async function pipeChannelsToResponse(channels, size, res) {
17450
17799
  failure = error instanceof Error ? error : new Error(String(error));
17451
17800
  wakeSlots();
17452
17801
  wakeChunks();
17802
+ wakeDrain();
17453
17803
  };
17454
17804
  const acquire = async () => {
17455
17805
  while (slots <= 0) await new Promise((resolve) => slotWaiters.push(resolve));
@@ -17521,17 +17871,27 @@ async function pipeChannelsToResponse(channels, size, res) {
17521
17871
  else chunkWaiters.set(index, resolve);
17522
17872
  });
17523
17873
  const waitDrain = () => new Promise((resolve) => {
17524
- if (cancelled || failure !== void 0) {
17874
+ if (cancelled || failure !== void 0 || res.destroyed) {
17525
17875
  resolve();
17526
17876
  return;
17527
17877
  }
17528
- res.once("drain", resolve);
17878
+ const done = () => {
17879
+ const at = drainWaiters.indexOf(done);
17880
+ if (at >= 0) drainWaiters.splice(at, 1);
17881
+ res.removeListener("drain", done);
17882
+ res.removeListener("close", done);
17883
+ resolve();
17884
+ };
17885
+ drainWaiters.push(done);
17886
+ res.once("drain", done);
17887
+ res.once("close", done);
17529
17888
  });
17530
17889
  const onResponseClose = () => {
17531
17890
  if (res.writableEnded) return;
17532
17891
  cancelled = true;
17533
17892
  wakeSlots();
17534
17893
  wakeChunks();
17894
+ wakeDrain();
17535
17895
  };
17536
17896
  res.on("close", onResponseClose);
17537
17897
  const idle = setInterval(() => {
@@ -17567,6 +17927,7 @@ async function pipeChannelsToResponse(channels, size, res) {
17567
17927
  cancelled = true;
17568
17928
  wakeSlots();
17569
17929
  wakeChunks();
17930
+ wakeDrain();
17570
17931
  await Promise.race([drained, new Promise((resolve) => setTimeout(resolve, 250))]);
17571
17932
  } else await drained;
17572
17933
  }
@@ -17600,7 +17961,7 @@ function closeAsync(sftp, handle) {
17600
17961
  * session teardown that follows settles it, so abandoning the wait is safe and
17601
17962
  * keeps a delivered download (or a finished upload) from pinning its channels.
17602
17963
  */
17603
- function closeQuietly(sftp, handle) {
17964
+ function closeQuietly$1(sftp, handle) {
17604
17965
  const abandoned = new Promise((resolve) => {
17605
17966
  setTimeout(resolve, HANDLE_CLOSE_TIMEOUT_MS).unref?.();
17606
17967
  });
@@ -17729,7 +18090,7 @@ function streamIntoFile(sftp, path, source, maxBytes) {
17729
18090
  if (handle !== void 0) {
17730
18091
  const current = handle;
17731
18092
  handle = void 0;
17732
- closeQuietly(sftp, current);
18093
+ closeQuietly$1(sftp, current);
17733
18094
  }
17734
18095
  reject(error);
17735
18096
  };
@@ -17767,7 +18128,7 @@ function streamIntoFile(sftp, path, source, maxBytes) {
17767
18128
  finish();
17768
18129
  return;
17769
18130
  }
17770
- closeQuietly(sftp, current).then(() => finish(), () => finish());
18131
+ closeQuietly$1(sftp, current).then(() => finish(), () => finish());
17771
18132
  };
17772
18133
  const enqueue = (buffer) => {
17773
18134
  chunks.set(nextChunk, buffer);
@@ -17895,6 +18256,122 @@ async function removeTree(sftp, dir) {
17895
18256
  }
17896
18257
  await rmdirAsync(sftp, dir);
17897
18258
  }
18259
+ /** Symlink hops a save is willing to follow before giving up. */
18260
+ const MAX_LINK_HOPS = 8;
18261
+ function readlinkAsync(sftp, path) {
18262
+ return new Promise((resolve, reject) => {
18263
+ sftp.readlink(path, (error, linkPath) => {
18264
+ if (error !== void 0 && error !== null) reject(error);
18265
+ else resolve(linkPath);
18266
+ });
18267
+ });
18268
+ }
18269
+ function setstatAsync(sftp, path, attrs) {
18270
+ return new Promise((resolve, reject) => {
18271
+ sftp.setstat(path, attrs, (error) => {
18272
+ if (error !== void 0 && error !== null) reject(error);
18273
+ else resolve();
18274
+ });
18275
+ });
18276
+ }
18277
+ /**
18278
+ * Resolve what a save must really write, following symbolic links.
18279
+ *
18280
+ * Writing a fresh inode over the path would replace the LINK with a regular file;
18281
+ * the base implementation wrote through the link (`writeFile` follows it), so
18282
+ * following it here keeps that meaning. The returned path is also where the side
18283
+ * file has to live: `rename` only stays inside one directory.
18284
+ *
18285
+ * A missing final target is not an error — saving through a dangling link (or
18286
+ * creating a new file) writes the target, exactly like `open('w')` did.
18287
+ */
18288
+ async function resolveWriteTarget(sftp, path) {
18289
+ let current = path;
18290
+ for (let hop = 0; hop <= MAX_LINK_HOPS; hop += 1) {
18291
+ let attrs;
18292
+ try {
18293
+ attrs = await lstatAsync(sftp, current);
18294
+ } catch (error) {
18295
+ if (error.code === SFTP_NO_SUCH_FILE) return {
18296
+ realPath: current,
18297
+ mode: void 0,
18298
+ size: void 0,
18299
+ mtime: void 0
18300
+ };
18301
+ throw error;
18302
+ }
18303
+ if (isSymlink(attrs.mode)) {
18304
+ current = posix.resolve(posix.dirname(current), await readlinkAsync(sftp, current));
18305
+ continue;
18306
+ }
18307
+ if (isDir(attrs.mode)) throw new Error(`not a file: ${current} is a directory`);
18308
+ return {
18309
+ realPath: current,
18310
+ mode: attrs.mode & 511,
18311
+ size: attrs.size,
18312
+ mtime: attrs.mtime * 1e3
18313
+ };
18314
+ }
18315
+ throw new Error(`too many symbolic links: ${path}`);
18316
+ }
18317
+ /**
18318
+ * One atomic replace through OpenSSH's `posix-rename@openssh.com` extension.
18319
+ *
18320
+ * @returns true when the server swapped the names in one step, false when it did
18321
+ * not advertise the extension — the only case the caller has to fall back for.
18322
+ */
18323
+ function posixRename(sftp, from, to) {
18324
+ return new Promise((resolve, reject) => {
18325
+ if (typeof sftp.ext_openssh_rename !== "function") {
18326
+ resolve(false);
18327
+ return;
18328
+ }
18329
+ try {
18330
+ sftp.ext_openssh_rename(from, to, (error) => {
18331
+ if (error === void 0 || error === null) resolve(true);
18332
+ else reject(error);
18333
+ });
18334
+ } catch (error) {
18335
+ if (/does not support this extended request/i.test(error instanceof Error ? error.message : String(error))) {
18336
+ resolve(false);
18337
+ return;
18338
+ }
18339
+ reject(error instanceof Error ? error : new Error(String(error)));
18340
+ }
18341
+ });
18342
+ }
18343
+ /**
18344
+ * Move a finished side file onto its target without ever deleting the target
18345
+ * before the replacement is in place.
18346
+ *
18347
+ * Atomic path: `posix-rename` (server-side name swap, no window at all).
18348
+ * Fallback: move the target aside, move the side file in, and swap the backup
18349
+ * back if that second rename fails — so the previous bytes exist at every moment
18350
+ * of the sequence. The failure keeps the REAL error: the old unlink-first code
18351
+ * reported `no such file` because it had already deleted the target by the time
18352
+ * the rename failed.
18353
+ *
18354
+ * The backup name carries 4 random bytes, so a leftover from a crash can never
18355
+ * collide with the next save's backup.
18356
+ */
18357
+ async function replaceFile(sftp, partial, target) {
18358
+ if (await posixRename(sftp, partial, target)) return;
18359
+ const backup = `${target}.bak-${randomBytes(4).toString("hex")}`;
18360
+ let hasBackup = false;
18361
+ try {
18362
+ await renameAsync(sftp, target, backup);
18363
+ hasBackup = true;
18364
+ } catch (error) {
18365
+ if (error.code !== SFTP_NO_SUCH_FILE) throw error;
18366
+ }
18367
+ try {
18368
+ await renameAsync(sftp, partial, target);
18369
+ } catch (error) {
18370
+ if (hasBackup) await renameAsync(sftp, backup, target).catch(() => void 0);
18371
+ throw error;
18372
+ }
18373
+ if (hasBackup) await unlinkAsync(sftp, backup).catch(() => void 0);
18374
+ }
17898
18375
  //#endregion
17899
18376
  //#region src/deploy.ts
17900
18377
  /**
@@ -17955,6 +18432,43 @@ function mapPlatform(unameS, unameM) {
17955
18432
  return "unknown";
17956
18433
  }
17957
18434
  const HEX64 = /^[0-9a-f]{64}$/;
18435
+ /**
18436
+ * Charset for a cached helper version.
18437
+ *
18438
+ * The version reaches a REMOTE shell line and remote directory names, so it is
18439
+ * not "just metadata": the sidecar in the cache directory (or a vendored copy
18440
+ * seeded into it) could otherwise smuggle `'`/`;` into the install script.
18441
+ * `-` is allowed only after the first character so the value cannot look like a
18442
+ * command-line option.
18443
+ */
18444
+ const HELPER_VERSION_RE = /^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/;
18445
+ /** Platforms `mapPlatform()` can produce; a cache entry must name one of them. */
18446
+ const HELPER_PLATFORMS = /* @__PURE__ */ new Set([
18447
+ "linux-x64",
18448
+ "linux-arm64",
18449
+ "macos-x64",
18450
+ "macos-arm64"
18451
+ ]);
18452
+ /** Resolve one cached tarball, or `undefined` when the name escapes the cache dir. */
18453
+ function safeHelperTarball(dir, tarball) {
18454
+ if (typeof tarball !== "string" || tarball === "" || tarball === "." || tarball === "..") return void 0;
18455
+ if (tarball.includes("/") || tarball.includes("\\")) return void 0;
18456
+ if (posix.basename(tarball) !== tarball) return void 0;
18457
+ const root = resolve(dir);
18458
+ const full = resolve(root, tarball);
18459
+ if (full !== join(root, tarball) || !full.startsWith(root + sep)) return void 0;
18460
+ try {
18461
+ return lstatSync(full).isFile() ? full : void 0;
18462
+ } catch {
18463
+ return;
18464
+ }
18465
+ }
18466
+ /** Absolute path of one cached helper tarball; throws when it is not inside the cache. */
18467
+ function helperTarballPath(helper, dir = helpersDir()) {
18468
+ const path = safeHelperTarball(dir, helper.tarball);
18469
+ if (path === void 0) throw new Error(`invalid helper tarball path: ${helper.tarball}`);
18470
+ return path;
18471
+ }
17958
18472
  /** Scan the local helper cache; invalid/incomplete entries are skipped. */
17959
18473
  function listCachedHelpers(dir = helpersDir()) {
17960
18474
  let names;
@@ -17974,11 +18488,13 @@ function listCachedHelpers(dir = helpersDir()) {
17974
18488
  const tarball = raw.tarball;
17975
18489
  const tarballSha256 = raw.tarballSha256;
17976
18490
  const binarySha256 = raw.binarySha256;
17977
- if (typeof version !== "string" || version === "") continue;
17978
- if (typeof platform !== "string" || platform === "") continue;
17979
- if (typeof tarball !== "string" || !existsSync(join(dir, tarball))) continue;
18491
+ const protocol = raw.protocol;
18492
+ if (typeof version !== "string" || !HELPER_VERSION_RE.test(version)) continue;
18493
+ if (typeof platform !== "string" || !HELPER_PLATFORMS.has(platform)) continue;
18494
+ if (safeHelperTarball(dir, tarball) === void 0) continue;
17980
18495
  if (typeof tarballSha256 !== "string" || !HEX64.test(tarballSha256)) continue;
17981
18496
  if (typeof binarySha256 !== "string" || !HEX64.test(binarySha256)) continue;
18497
+ if (typeof protocol !== "number" || !Number.isInteger(protocol) || protocol <= 0) continue;
17982
18498
  entries.push({
17983
18499
  kind: "executable",
17984
18500
  version,
@@ -17986,17 +18502,57 @@ function listCachedHelpers(dir = helpersDir()) {
17986
18502
  tarball,
17987
18503
  tarballSha256,
17988
18504
  binarySha256,
17989
- protocol: typeof raw.protocol === "number" ? raw.protocol : 0,
18505
+ protocol,
17990
18506
  nodeVersion: typeof raw.nodeVersion === "string" ? raw.nodeVersion : ""
17991
18507
  });
17992
18508
  } catch {}
17993
18509
  }
17994
- entries.sort((a, b) => a.version < b.version ? 1 : a.version > b.version ? -1 : 0);
18510
+ entries.sort(compareHelperVersionsDesc);
17995
18511
  return entries;
17996
18512
  }
17997
- /** Pick a cached build for a platform (exact version pin or newest). */
17998
- function pickCached(platform, version) {
17999
- const matches = listCachedHelpers().filter((h) => h.platform === platform);
18513
+ /**
18514
+ * SemVer-ish comparison for cached helper versions.
18515
+ *
18516
+ * A plain string compare picked `0.9.0` over `0.10.0` (multi-digit segments sort
18517
+ * wrong: `9` > `10`) and the pipeline then pushed an OLD helper as "ok". Numeric
18518
+ * segments compare as numbers, everything else lexicographically; a shorter
18519
+ * version loses to its own extension (`0.2` < `0.2.1`) and a numeric segment wins
18520
+ * over a pre-release one (`0.2.1` > `0.2.1-alpha.2`).
18521
+ */
18522
+ function compareHelperVersions(left, right) {
18523
+ const split = (value) => value.split(/[.+-]/);
18524
+ const a = split(left);
18525
+ const b = split(right);
18526
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
18527
+ const x = a[index];
18528
+ const y = b[index];
18529
+ if (x === void 0) return y !== void 0 && /^\d+$/.test(y) ? -1 : 1;
18530
+ if (y === void 0) return x !== void 0 && /^\d+$/.test(x) ? 1 : -1;
18531
+ const nx = /^\d+$/.test(x) ? Number(x) : void 0;
18532
+ const ny = /^\d+$/.test(y) ? Number(y) : void 0;
18533
+ if (nx !== void 0 && ny !== void 0) {
18534
+ if (nx !== ny) return nx < ny ? -1 : 1;
18535
+ continue;
18536
+ }
18537
+ if (nx !== void 0) return -1;
18538
+ if (ny !== void 0) return 1;
18539
+ if (x !== y) return x < y ? -1 : 1;
18540
+ }
18541
+ return 0;
18542
+ }
18543
+ /** Newest first (Array.prototype.sort comparator). */
18544
+ function compareHelperVersionsDesc(a, b) {
18545
+ return compareHelperVersions(b.version, a.version);
18546
+ }
18547
+ /**
18548
+ * Pick a cached build for a platform (exact version pin or newest).
18549
+ *
18550
+ * `expectedProtocol` (default: this plugin's wire protocol) is part of the
18551
+ * choice: a cached build whose protocol does not match would install fine and
18552
+ * then fail the runtime handshake, so it is not a candidate at all.
18553
+ */
18554
+ function pickCached(platform, version, expectedProtocol = 2) {
18555
+ const matches = listCachedHelpers().filter((h) => h.platform === platform && h.protocol === expectedProtocol);
18000
18556
  if (version !== void 0 && version !== "") return matches.find((h) => h.version === version);
18001
18557
  return matches[0];
18002
18558
  }
@@ -18257,6 +18813,40 @@ async function pushProbeBundle(pool, store, alias, probed, home, started) {
18257
18813
  };
18258
18814
  }
18259
18815
  }
18816
+ /**
18817
+ * Remote shell steps installing one cached helper.
18818
+ *
18819
+ * Invariant: the currently installed version is never deleted before the new one
18820
+ * is fully extracted — the old dir is renamed to `.old` and removed only after
18821
+ * the swap, and a crash between "old moved away" and "new moved in" is repaired
18822
+ * by the recovery step (restore `.old` when the live dir is missing). Every path
18823
+ * goes through `shRoot`; the tarball name embedded in the sha256 line is quoted
18824
+ * too (the caller's version already passed `HELPER_VERSION_RE`, so it cannot
18825
+ * break out of the shell any more).
18826
+ *
18827
+ * Pure string work (no fs/pool) so a gate can pin the ORDER without a remote.
18828
+ */
18829
+ function helperInstallSteps(helper, paths) {
18830
+ const { root, verDir, tmpFile } = paths;
18831
+ return [
18832
+ `cd ${shRoot(root)}`,
18833
+ `echo ${shRoot(`${helper.tarballSha256} ${posix.basename(tmpFile)}`)} | sha256sum -c --status -`,
18834
+ `if [ ! -d ${shRoot(verDir)} ] && [ -d ${shRoot(verDir + ".old")} ]; then mv ${shRoot(verDir + ".old")} ${shRoot(verDir)}; fi`,
18835
+ `rm -rf ${shRoot(verDir + ".next")}`,
18836
+ `mkdir -p ${shRoot(verDir + ".next")}`,
18837
+ `tar -xzf ${shRoot(tmpFile)} -C ${shRoot(verDir + ".next")} --strip-components=1`,
18838
+ `rm -f ${shRoot(tmpFile)}`,
18839
+ `rm -rf ${shRoot(verDir + ".old")}`,
18840
+ `if [ -d ${shRoot(verDir)} ]; then mv ${shRoot(verDir)} ${shRoot(verDir + ".old")}; fi`,
18841
+ `mv ${shRoot(verDir + ".next")} ${shRoot(verDir)}`,
18842
+ `rm -rf ${shRoot(verDir + ".old")}`,
18843
+ `echo "RV_DIGEST=$(sha256sum ${shRoot(verDir + "/dsh-ssh-helper")} | cut -d' ' -f1)"`
18844
+ ];
18845
+ }
18846
+ /** One POSIX shell line: steps joined so any failure stops the sequence. */
18847
+ function helperInstallScript(helper, paths) {
18848
+ return helperInstallSteps(helper, paths).join(" && ");
18849
+ }
18260
18850
  /** P1 path: push a cached helper tarball, verify, extract, manifest. */
18261
18851
  async function pushHelper(pool, store, alias, probed, home, helper, started) {
18262
18852
  const artifact = `dsh-ssh-helper/${helper.version}`;
@@ -18289,25 +18879,20 @@ async function pushHelper(pool, store, alias, probed, home, helper, started) {
18289
18879
  };
18290
18880
  }
18291
18881
  const root = `${home}/.dsh-helpers`;
18292
- const verDir = `${root}/dsh-ssh-helper-${helper.version}-${helper.platform}`;
18293
- const tmpFile = `${root}/.tmp-${helper.version}-${Date.now()}.tar.gz`;
18882
+ const manifestPath = `${root}/manifest.json`;
18883
+ const manifestNext = `${root}/manifest.json.next`;
18884
+ const paths = {
18885
+ root,
18886
+ verDir: `${root}/dsh-ssh-helper-${helper.version}-${helper.platform}`,
18887
+ tmpFile: `${root}/.tmp-${helper.version}-${Date.now()}.tar.gz`
18888
+ };
18294
18889
  try {
18295
18890
  const files = new RemoteFiles(pool);
18296
18891
  await files.mkdir(alias, root);
18297
- await pool.putFile(alias, join(helpersDir(), helper.tarball), tmpFile);
18298
- const install = [
18299
- `cd ${shRoot(root)}`,
18300
- `echo '${helper.tarballSha256} ${tmpFile.split("/").pop()}' | sha256sum -c --status -`,
18301
- `rm -rf ${shRoot(verDir + ".new")} ${shRoot(verDir)}`,
18302
- `mkdir -p ${shRoot(verDir + ".new")}`,
18303
- `tar -xzf ${shRoot(tmpFile)} -C ${shRoot(verDir + ".new")} --strip-components=1`,
18304
- `rm -f ${shRoot(tmpFile)}`,
18305
- `mv ${shRoot(verDir + ".new")} ${shRoot(verDir)}`,
18306
- `echo "RV_DIGEST=$(sha256sum ${shRoot(verDir + "/dsh-ssh-helper")} | cut -d' ' -f1)"`
18307
- ].join(" && ");
18308
- const installed = await pool.exec(alias, install, { timeoutMs: 18e4 });
18309
- if (!installed.success) throw new Error(`remote install failed [exit code: ${installed.exitCode}]: ${installed.stderr || installed.stdout || installed.error || "unknown"}`);
18310
- const digestMatch = /^RV_DIGEST=([0-9a-fA-F]{64})$/m.exec(installed.stdout);
18892
+ await pool.putFile(alias, helperTarballPath(helper), paths.tmpFile);
18893
+ const installedRun = await pool.exec(alias, helperInstallScript(helper, paths), { timeoutMs: 18e4 });
18894
+ if (!installedRun.success) throw new Error(`remote install failed [exit code: ${installedRun.exitCode}]: ${installedRun.stderr || installedRun.stdout || installedRun.error || "unknown"}`);
18895
+ const digestMatch = /^RV_DIGEST=([0-9a-fA-F]{64})$/m.exec(installedRun.stdout);
18311
18896
  const digest = digestMatch !== null ? digestMatch[1].toLowerCase() : "";
18312
18897
  if (digest === "" || digest !== helper.binarySha256) throw new Error(`binary digest mismatch after extract: got ${digest || "(unparsed)"} want ${helper.binarySha256}`);
18313
18898
  const manifest = {
@@ -18317,7 +18902,9 @@ async function pushHelper(pool, store, alias, probed, home, helper, started) {
18317
18902
  helper: helperRef,
18318
18903
  installedAt: Date.now()
18319
18904
  };
18320
- await files.write(alias, `${root}/manifest.json`, JSON.stringify(manifest, null, 2) + "\n");
18905
+ await files.write(alias, manifestNext, JSON.stringify(manifest, null, 2) + "\n");
18906
+ const renamed = await pool.exec(alias, `mv ${shRoot(manifestNext)} ${shRoot(manifestPath)}`, { timeoutMs: 15e3 });
18907
+ if (!renamed.success) throw new Error(`manifest rename failed [exit code: ${renamed.exitCode}]: ${renamed.stderr || renamed.error || "unknown"}`);
18321
18908
  const detail = `pushed ${artifact} (${helper.platform}, bin ${helper.binarySha256.slice(0, 12)}…) in ${Date.now() - started} ms`;
18322
18909
  store.setDeploy(alias, {
18323
18910
  status: "ok",
@@ -18339,7 +18926,13 @@ async function pushHelper(pool, store, alias, probed, home, helper, started) {
18339
18926
  } catch (error) {
18340
18927
  const detail = `push failed: ${error instanceof Error ? error.message : String(error)}`;
18341
18928
  store.setDeploy(alias, failedState(store, alias, artifact, detail));
18342
- await pool.exec(alias, `rm -f ${shRoot(tmpFile)}; rm -rf ${shRoot(verDir + ".new")}`, { timeoutMs: 15e3 }).catch(() => void 0);
18929
+ const cleanup = [
18930
+ `rm -f ${shRoot(paths.tmpFile)}`,
18931
+ `rm -rf ${shRoot(paths.verDir + ".next")}`,
18932
+ `rm -f ${shRoot(manifestNext)}`,
18933
+ `if [ ! -d ${shRoot(paths.verDir)} ] && [ -d ${shRoot(paths.verDir + ".old")} ]; then mv ${shRoot(paths.verDir + ".old")} ${shRoot(paths.verDir)}; fi`
18934
+ ].join("; ");
18935
+ await pool.exec(alias, cleanup, { timeoutMs: 15e3 }).catch(() => void 0);
18343
18936
  return {
18344
18937
  alias,
18345
18938
  probe: probed,
@@ -18350,7 +18943,13 @@ async function pushHelper(pool, store, alias, probed, home, helper, started) {
18350
18943
  };
18351
18944
  }
18352
18945
  }
18353
- /** Single-quote a remote path for sh (paths here are probe-derived + fixed names). */
18946
+ /**
18947
+ * Single-quote a remote path for sh.
18948
+ *
18949
+ * Paths are probe-derived, but the version/platform segments come from a cache
18950
+ * sidecar: they pass `HELPER_VERSION_RE`/`HELPER_PLATFORMS` before ever reaching
18951
+ * this function, so the quoting here is the second layer, not the only one.
18952
+ */
18354
18953
  function shRoot(path) {
18355
18954
  if (path.includes("\0")) throw new Error("invalid path");
18356
18955
  return `'${path.replace(/'/g, `'\\''`)}'`;
@@ -18505,6 +19104,24 @@ var HelperTimeoutError = class extends Error {
18505
19104
  this.name = "HelperTimeoutError";
18506
19105
  }
18507
19106
  };
19107
+ /**
19108
+ * Close each resource, ignoring failures — and keeping going.
19109
+ *
19110
+ * Teardown runs while an error is already unwinding: one resource that throws on
19111
+ * close must not stop the NEXT one from being released (that skipped socket is
19112
+ * exactly the leak this exists to prevent). Exported so the gate can drive the
19113
+ * real behaviour with fake resources; there is no transport to stub locally.
19114
+ */
19115
+ function closeQuietly(resources) {
19116
+ for (const resource of resources) {
19117
+ try {
19118
+ resource.close?.();
19119
+ } catch {}
19120
+ try {
19121
+ resource.end?.();
19122
+ } catch {}
19123
+ }
19124
+ }
18508
19125
  var RpcConnection = class {
18509
19126
  opts;
18510
19127
  conn;
@@ -18583,24 +19200,13 @@ var RpcConnection = class {
18583
19200
  */
18584
19201
  async reconnect() {
18585
19202
  if (this.disposed) throw new Error("helper RPC was disposed");
18586
- try {
18587
- this.peer?.close();
18588
- } catch {}
18589
- try {
18590
- this.channel?.close();
18591
- } catch {}
18592
- try {
18593
- this.conn?.end();
18594
- } catch {}
18595
- if (this.heartbeat !== void 0) clearTimeout(this.heartbeat);
18596
- this.peer = void 0;
18597
- this.channel = void 0;
18598
- this.conn = void 0;
19203
+ this.teardownTransport();
18599
19204
  this.dead = void 0;
18600
19205
  this.readyPromise = this.open();
18601
19206
  try {
18602
19207
  await this.readyPromise;
18603
19208
  } catch (error) {
19209
+ this.teardownTransport();
18604
19210
  this.readyPromise = void 0;
18605
19211
  throw error;
18606
19212
  }
@@ -18608,26 +19214,52 @@ var RpcConnection = class {
18608
19214
  async dispose() {
18609
19215
  if (this.disposed) return;
18610
19216
  this.disposed = true;
18611
- if (this.heartbeat !== void 0) clearTimeout(this.heartbeat);
18612
- try {
18613
- this.peer?.close();
18614
- } catch {}
18615
- try {
18616
- this.channel?.close();
18617
- } catch {}
18618
- try {
18619
- this.conn?.end();
18620
- } catch {}
19217
+ this.teardownTransport();
18621
19218
  }
18622
19219
  async peerReady() {
18623
19220
  await this.ready;
18624
19221
  if (this.peer === void 0 || this.dead !== void 0) throw this.dead ?? /* @__PURE__ */ new Error("helper RPC is not connected");
18625
19222
  return this.peer;
18626
19223
  }
19224
+ /**
19225
+ * Release the current transport, whatever state it is in.
19226
+ *
19227
+ * Shared by `reconnect()`, a failed `open()` and `dispose()` because all three
19228
+ * carry the same obligation: afterwards no ssh session, channel or heartbeat may
19229
+ * survive. A half-open transport is a real leak — the socket lives until the
19230
+ * remote's keepalive gives up, and the next attempt opens a SECOND session.
19231
+ * `stderrTail` is cleared too: it describes the connection being torn down, and
19232
+ * keeping it would attribute the NEXT failure to the previous transport's error
19233
+ * output.
19234
+ */
19235
+ teardownTransport() {
19236
+ if (this.heartbeat !== void 0) {
19237
+ clearTimeout(this.heartbeat);
19238
+ this.heartbeat = void 0;
19239
+ }
19240
+ const resources = [];
19241
+ if (this.peer !== void 0) resources.push(this.peer);
19242
+ if (this.channel !== void 0) resources.push(this.channel);
19243
+ if (this.conn !== void 0) resources.push(this.conn);
19244
+ closeQuietly(resources);
19245
+ this.peer = void 0;
19246
+ this.channel = void 0;
19247
+ this.conn = void 0;
19248
+ this.stderrTail = "";
19249
+ }
18627
19250
  async open() {
18628
- const { entry } = this.opts;
18629
19251
  const conn = new import_lib.Client();
18630
19252
  this.conn = conn;
19253
+ try {
19254
+ return await this.dialAndHello(conn);
19255
+ } catch (error) {
19256
+ this.teardownTransport();
19257
+ throw error;
19258
+ }
19259
+ }
19260
+ /** The part of {@link open} that runs once the socket object exists. */
19261
+ async dialAndHello(conn) {
19262
+ const { entry } = this.opts;
18631
19263
  await new Promise((resolve, reject) => {
18632
19264
  let settled = false;
18633
19265
  conn.on("ready", () => {
@@ -19099,6 +19731,23 @@ var RemoteWorlds = class {
19099
19731
  const result = await this.deps.pool.exec(alias, `mkdir -p ${quoted} && chmod 700 ${quoted}`, { timeoutMs: 15e3 });
19100
19732
  if (!result.success) throw new Error(`remote mkdir failed: ${result.stderr || result.error || `exit ${result.exitCode}`}`);
19101
19733
  }
19734
+ /**
19735
+ * TTL-sweep one host's spill root (retention, best effort).
19736
+ *
19737
+ * Deliberately narrow: the command is built by `spill-retention.ts` (absolute
19738
+ * path under that host's `$HOME`, `session-*` children only, depth 1), so this
19739
+ * method cannot be talked into deleting an arbitrary directory. Callers treat a
19740
+ * rejection as a warning, never as an operation failure.
19741
+ */
19742
+ async sweepSpillRoot(alias, home, ttlDays) {
19743
+ const result = await this.deps.pool.exec(alias, spillSweepCommand(home, ttlDays), { timeoutMs: 2e4 });
19744
+ if (!result.success) throw new Error(`remote spill sweep failed: ${result.stderr || result.error || `exit ${result.exitCode}`}`);
19745
+ }
19746
+ /** Remove one session's spill directory when it is older than the TTL (best effort). */
19747
+ async sweepSpillDir(alias, dir, ttlDays) {
19748
+ const result = await this.deps.pool.exec(alias, spillDirSweepCommand(dir, ttlDays), { timeoutMs: 2e4 });
19749
+ if (!result.success) throw new Error(`remote spill dir sweep failed: ${result.stderr || result.error || `exit ${result.exitCode}`}`);
19750
+ }
19102
19751
  /** Drop one host's RPC + fs view + proc runtime (call after host update/delete). */
19103
19752
  async dropHost(alias) {
19104
19753
  this.fsReady.delete(alias);
@@ -19314,4 +19963,4 @@ var RemoteWorlds = class {
19314
19963
  }
19315
19964
  };
19316
19965
  //#endregion
19317
- export { pushPipeline as a, attachmentHeader as c, dshHome as d, ensurePrivateDir as f, probe as i, require_lib as l, storePath as m, isWindowsAbsolute as n, seedHelperCache as o, keysDir as p, helperAvailability as r, RemoteFiles as s, RemoteWorlds as t, aliasRoot as u };
19966
+ export { storePath as C, keysDir as S, resolveTimeouts as _, pushPipeline as a, dshHome as b, WriteConflictError as c, DEFAULT_READ_TIMEOUT_MS as d, DEFAULT_TIMEOUTS as f, clampExecTimeout as g, MIN_TIMEOUT_MS as h, probe as i, attachmentHeader as l, MAX_TIMEOUT_MS as m, isWindowsAbsolute as n, seedHelperCache as o, DeadlineError as p, helperAvailability as r, RemoteFiles as s, RemoteWorlds as t, DEFAULT_GIT_TIMEOUT_MS as u, require_lib as v, ensurePrivateDir as x, aliasRoot as y };