dsh-remote-vs 0.28.0 → 0.30.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.
Files changed (46) hide show
  1. package/README.en.md +63 -7
  2. package/README.md +51 -7
  3. package/lib/client.js +393 -112
  4. package/lib/index.js +2271 -160
  5. package/lib/p2-router-fs.js +1 -1
  6. package/lib/types/changes/recorder.d.ts +65 -10
  7. package/lib/types/changes/status.d.ts +48 -3
  8. package/lib/types/client/ConnectionsSection.d.ts +73 -0
  9. package/lib/types/client/HostsView.d.ts +139 -2
  10. package/lib/types/client/api.d.ts +65 -2
  11. package/lib/types/client/connection.d.ts +28 -1
  12. package/lib/types/client/scm/actions.d.ts +25 -1
  13. package/lib/types/forward.d.ts +11 -1
  14. package/lib/types/p2/helper-rpc.d.ts +48 -0
  15. package/lib/types/p2/worlds.d.ts +28 -0
  16. package/lib/types/pool.d.ts +337 -8
  17. package/lib/types/protocol.d.ts +218 -0
  18. package/lib/types/proxy.d.ts +136 -0
  19. package/lib/types/store.d.ts +81 -1
  20. package/lib/types/tools.d.ts +3 -0
  21. package/lib/{worlds-RG8K5eom.js → worlds-CRRZMZhg.js} +85 -6
  22. package/package.json +1 -1
  23. package/src/changes/recorder.ts +151 -15
  24. package/src/changes/status.ts +59 -4
  25. package/src/client/ConnectionStatus.tsx +19 -5
  26. package/src/client/ConnectionsSection.tsx +359 -0
  27. package/src/client/HostsView.tsx +552 -11
  28. package/src/client/MonitorView.tsx +14 -0
  29. package/src/client/PortsView.tsx +16 -0
  30. package/src/client/SettingsHosts.tsx +132 -6
  31. package/src/client/api.ts +102 -4
  32. package/src/client/connection.ts +76 -2
  33. package/src/client/i18n.ts +152 -2
  34. package/src/client/scm/actions.ts +63 -12
  35. package/src/client/vsc/vsc.css +281 -0
  36. package/src/forward.ts +38 -2
  37. package/src/importers.ts +125 -13
  38. package/src/keygen.ts +8 -1
  39. package/src/p2/helper-rpc.ts +73 -5
  40. package/src/p2/worlds.ts +48 -0
  41. package/src/pool.ts +1120 -100
  42. package/src/protocol.ts +228 -0
  43. package/src/proxy.ts +673 -0
  44. package/src/routes.ts +139 -5
  45. package/src/store.ts +335 -0
  46. package/src/tools.ts +47 -2
package/lib/index.js CHANGED
@@ -1,16 +1,622 @@
1
- import { C as dshHome, D as viewSettingsPath, E as storePath, S as aliasRoot, T as keysDir, _ as MAX_TIMEOUT_MS, a as takeHostNotices, b as resolveTimeouts, c as pushPipeline, d as WriteConflictError, f as attachmentHeader, g as DeadlineError, h as DEFAULT_TIMEOUTS, i as drainHostNotices, l as seedHelperCache, m as DEFAULT_READ_TIMEOUT_MS, n as TombstonedError, o as helperAvailability, p as DEFAULT_GIT_TIMEOUT_MS, s as probe, t as RemoteWorlds, u as RemoteFiles, v as MIN_TIMEOUT_MS, w as ensurePrivateDir, x as require_lib, y as clampExecTimeout } from "./worlds-RG8K5eom.js";
1
+ import { C as dshHome, D as viewSettingsPath, E as storePath, S as aliasRoot, T as keysDir, _ as MAX_TIMEOUT_MS, a as takeHostNotices, b as resolveTimeouts, c as pushPipeline, d as WriteConflictError, f as attachmentHeader, g as DeadlineError, h as DEFAULT_TIMEOUTS, i as drainHostNotices, l as seedHelperCache, m as DEFAULT_READ_TIMEOUT_MS, n as TombstonedError, o as helperAvailability, p as DEFAULT_GIT_TIMEOUT_MS, s as probe, t as RemoteWorlds, u as RemoteFiles, v as MIN_TIMEOUT_MS, w as ensurePrivateDir, x as require_lib, y as clampExecTimeout } from "./worlds-CRRZMZhg.js";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, statSync, writeSync } from "node:fs";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { dirname, join, posix } from "node:path";
6
6
  import { homedir } from "node:os";
7
+ import { createConnection, createServer } from "node:net";
7
8
  import { StringDecoder } from "node:string_decoder";
8
9
  import { fileURLToPath } from "node:url";
9
- import { createServer } from "node:net";
10
10
  import { WebSocketServer } from "ws";
11
11
  import { execFile } from "node:child_process";
12
12
  import { promisify } from "node:util";
13
13
  import { defineTool } from "@deepseek-ai/dsh-tools";
14
+ //#region src/proxy.ts
15
+ /**
16
+ * Outbound proxy support for SSH dials.
17
+ *
18
+ * Why this is not just `HTTP_PROXY`: ssh2 dials a raw TCP socket, and the
19
+ * harness's proxy plumbing (`@deepseek-ai/dsh-http-proxy`) only wraps `fetch`,
20
+ * so a host that can only be reached through a proxy needs the tunnel built
21
+ * here. Three flavours, in the order a user meets them:
22
+ *
23
+ * - `http` — `CONNECT host:port`, optional `Proxy-Authorization: Basic …`;
24
+ * - `socks5` — greeting / optional user+password sub-negotiation / CONNECT;
25
+ * - jump (`ProxyJump` / `ProxyCommand ssh -W`) — NOT dialled here: the pool
26
+ * opens a `direct-tcpip` channel on ANOTHER pooled connection and hands it
27
+ * to ssh2 as its socket. This module only parses those specs into a target.
28
+ *
29
+ * **Error taxonomy is the point.** "The proxy refused the tunnel" and "the
30
+ * target closed the port" and "your password is wrong" all fail the dial, and
31
+ * the user debugs the wrong thing if they all read "connection failed". Each
32
+ * failure therefore leaves as a `ProxyError` with a stable `reason` and one
33
+ * actionable sentence.
34
+ *
35
+ * **Bytes are never lost.** A proxy may send tunnel bytes in the same packet as
36
+ * its handshake reply; everything read past the handshake is pushed back onto
37
+ * the socket before it is handed to ssh2, or the SSH banner would be swallowed
38
+ * and the handshake would stall.
39
+ *
40
+ * @module
41
+ */
42
+ /** A proxy dial failure that knows which layer broke. */
43
+ var ProxyError = class extends Error {
44
+ reason;
45
+ kind;
46
+ constructor(reason, message, kind) {
47
+ super(message);
48
+ this.reason = reason;
49
+ this.kind = kind;
50
+ this.name = "ProxyError";
51
+ }
52
+ };
53
+ /** Hostname / IPv4 / IPv6 accepted as a proxy or destination. */
54
+ const HOST_RE = /^[A-Za-z0-9._:[\]%-]{1,255}$/;
55
+ /** Longest credential string accepted (a proxy config, not a password manager). */
56
+ const MAX_CREDENTIAL = 255;
57
+ function cleanCredential(value) {
58
+ if (typeof value !== "string") return void 0;
59
+ if (value === "") return void 0;
60
+ return value.length > MAX_CREDENTIAL ? value.slice(0, MAX_CREDENTIAL) : value;
61
+ }
62
+ /**
63
+ * Validate one proxy endpoint.
64
+ *
65
+ * @param input - value as it arrived from the browser / store file.
66
+ * @returns the normalized config (empty credentials dropped).
67
+ * @throws {ProxyError} `target` when a field is unusable, with the field named.
68
+ */
69
+ function normalizeProxy(input) {
70
+ if (typeof input !== "object" || input === null) throw new ProxyError("target", "proxy must be an object");
71
+ const raw = input;
72
+ const kind = raw.kind;
73
+ if (kind !== "http" && kind !== "socks5") throw new ProxyError("target", "proxy.kind must be 'http' or 'socks5'");
74
+ if (typeof raw.host !== "string" || !HOST_RE.test(raw.host)) throw new ProxyError("target", "proxy.host must be a hostname or IP address");
75
+ const port = raw.port;
76
+ if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) throw new ProxyError("target", "proxy.port must be an integer between 1 and 65535");
77
+ const username = cleanCredential(raw.username);
78
+ const password = cleanCredential(raw.password);
79
+ return {
80
+ kind,
81
+ host: raw.host,
82
+ port,
83
+ ...username === void 0 ? {} : { username },
84
+ ...password === void 0 ? {} : { password }
85
+ };
86
+ }
87
+ /** One `user@host:port` hop of a ProxyJump chain. */
88
+ function parseHop(token) {
89
+ const at = token.lastIndexOf("@");
90
+ const user = at < 0 ? void 0 : token.slice(0, at);
91
+ const rest = at < 0 ? token : token.slice(at + 1);
92
+ if (rest === "") return void 0;
93
+ if (rest.includes(" [") || /\s/.test(rest)) return void 0;
94
+ let host = rest;
95
+ let port = 22;
96
+ const bracket = /^\[(.+)\]:(\d+)$/.exec(rest);
97
+ if (bracket !== null) {
98
+ host = `[${bracket[1]}]`;
99
+ port = Number.parseInt(bracket[2] ?? "", 10);
100
+ } else if (rest.startsWith("[") && rest.endsWith("]")) host = rest;
101
+ else {
102
+ const colon = rest.lastIndexOf(":");
103
+ if (colon > 0) {
104
+ const tail = rest.slice(colon + 1);
105
+ if (/^\d+$/.test(tail)) {
106
+ host = rest.slice(0, colon);
107
+ port = Number.parseInt(tail, 10);
108
+ }
109
+ }
110
+ }
111
+ if (!HOST_RE.test(host)) return void 0;
112
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return void 0;
113
+ return {
114
+ ...user === void 0 || user === "" ? {} : { user },
115
+ host,
116
+ port
117
+ };
118
+ }
119
+ /**
120
+ * Parse an OpenSSH `ProxyJump` value (`jump`, `user@jump:2222`, `a,b`).
121
+ *
122
+ * Only a single hop is supported: the pool builds the tunnel on one existing
123
+ * pooled connection, and a chain would need nested channels whose failure modes
124
+ * we cannot explain to the user yet. Multi-hop is therefore a named refusal
125
+ * rather than a silent half-feature.
126
+ */
127
+ function parseProxyJump(value) {
128
+ const hops = value.split(",").map((hop) => hop.trim()).filter((hop) => hop !== "");
129
+ if (hops.length === 0) return {
130
+ ok: false,
131
+ reason: "ProxyJump names no host"
132
+ };
133
+ if (hops.length > 1) return {
134
+ ok: false,
135
+ reason: `ProxyJump with ${hops.length} hops is not supported (one jump host only)`
136
+ };
137
+ const target = parseHop(hops[0] ?? "");
138
+ if (target === void 0) return {
139
+ ok: false,
140
+ reason: "ProxyJump must look like user@host:port"
141
+ };
142
+ return {
143
+ ok: true,
144
+ target
145
+ };
146
+ }
147
+ /** One tokenized ProxyCommand word (quotes dropped, `%h`/`%p` kept verbatim). */
148
+ function tokenize(command) {
149
+ const out = [];
150
+ let current = "";
151
+ let quote;
152
+ for (const char of command) {
153
+ if (quote !== void 0) {
154
+ if (char === quote) quote = void 0;
155
+ else current += char;
156
+ continue;
157
+ }
158
+ if (char === "\"" || char === "'") {
159
+ quote = char;
160
+ continue;
161
+ }
162
+ if (/\s/.test(char)) {
163
+ if (current !== "") out.push(current);
164
+ current = "";
165
+ continue;
166
+ }
167
+ current += char;
168
+ }
169
+ if (current !== "") out.push(current);
170
+ return out;
171
+ }
172
+ /** `host:port` used by nc/ncat proxy arguments. */
173
+ function parseProxyAddress(value) {
174
+ const colon = value.lastIndexOf(":");
175
+ if (colon <= 0) return void 0;
176
+ const host = value.slice(0, colon);
177
+ const port = Number.parseInt(value.slice(colon + 1), 10);
178
+ if (!HOST_RE.test(host)) return void 0;
179
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return void 0;
180
+ return {
181
+ host,
182
+ port
183
+ };
184
+ }
185
+ /**
186
+ * Map the ProxyCommand forms users actually write onto a tunnel we can build.
187
+ *
188
+ * Recognised: `ssh … -W %h:%p [user@]host`, `nc -X connect -x host:port %h %p`
189
+ * (http), `nc -x host:port %h %p` (socks5), `ncat --proxy … --proxy-type …`.
190
+ * Everything else is refused by name — a ProxyCommand is a shell command, and
191
+ * running one from a browser-supplied config is not a feature this plugin
192
+ * offers.
193
+ */
194
+ function parseProxyCommand(command) {
195
+ const words = tokenize(command);
196
+ if (words.length === 0) return {
197
+ kind: "unsupported",
198
+ reason: "ProxyCommand is empty"
199
+ };
200
+ const program = (words[0] ?? "").split(/[\\/]/).pop() ?? "";
201
+ if (program === "ssh") {
202
+ /**
203
+ * `ssh -W %h:%p bastion` — the canonical ProxyCommand — puts the DESTINATION
204
+ * in `-W`'s argument and the JUMP HOST in the positional argument. Reading
205
+ * `-W`'s value as the jump host is the mistake this loop exists to avoid:
206
+ * it is always the literal `%h:%p`.
207
+ */
208
+ let forwards = false;
209
+ let user;
210
+ let port;
211
+ let destination;
212
+ for (let index = 1; index < words.length; index += 1) {
213
+ const word = words[index] ?? "";
214
+ if (word === "-W" || word.startsWith("-W")) {
215
+ forwards = true;
216
+ if (word === "-W") index += 1;
217
+ continue;
218
+ }
219
+ if (word === "-l" || word === "-p" || word === "-o" || word === "-i" || word === "-F" || word === "-J") {
220
+ const value = words[index + 1];
221
+ if (word === "-l") user = value;
222
+ if (word === "-p") {
223
+ const parsedPort = Number.parseInt(value ?? "", 10);
224
+ if (Number.isInteger(parsedPort) && parsedPort > 0 && parsedPort <= 65535) port = parsedPort;
225
+ }
226
+ index += 1;
227
+ continue;
228
+ }
229
+ if (word.startsWith("-")) continue;
230
+ destination ??= word;
231
+ }
232
+ if (!forwards) return {
233
+ kind: "unsupported",
234
+ reason: "ProxyCommand ssh must use -W %h:%p"
235
+ };
236
+ if (destination === void 0) return {
237
+ kind: "unsupported",
238
+ reason: "ProxyCommand ssh -W names no jump host"
239
+ };
240
+ const parsed = parseHop(user === void 0 || user === "" ? destination : `${user}@${destination}`);
241
+ if (parsed === void 0) return {
242
+ kind: "unsupported",
243
+ reason: "ProxyCommand ssh -W: the jump host is not a host name"
244
+ };
245
+ return {
246
+ kind: "jump",
247
+ target: {
248
+ ...parsed,
249
+ ...port === void 0 ? {} : { port }
250
+ }
251
+ };
252
+ }
253
+ if (program === "nc" || program === "netcat") {
254
+ const x = words.indexOf("-X");
255
+ const xMode = x < 0 ? void 0 : words[x + 1] ?? "";
256
+ const dash = words.indexOf("-x");
257
+ const address = dash < 0 ? void 0 : parseProxyAddress(words[dash + 1] ?? "");
258
+ if (address === void 0) return {
259
+ kind: "unsupported",
260
+ reason: "ProxyCommand nc must name a proxy with -x host:port"
261
+ };
262
+ if (xMode === "connect" || xMode === "http") return {
263
+ kind: "proxy",
264
+ proxy: {
265
+ kind: "http",
266
+ ...address
267
+ }
268
+ };
269
+ if (xMode === void 0 || xMode === "5" || xMode === "socks5") return {
270
+ kind: "proxy",
271
+ proxy: {
272
+ kind: "socks5",
273
+ ...address
274
+ }
275
+ };
276
+ return {
277
+ kind: "unsupported",
278
+ reason: `ProxyCommand nc -X ${xMode} is not supported`
279
+ };
280
+ }
281
+ if (program === "ncat") {
282
+ const at = words.indexOf("--proxy");
283
+ const address = at < 0 ? void 0 : parseProxyAddress(words[at + 1] ?? "");
284
+ if (address === void 0) return {
285
+ kind: "unsupported",
286
+ reason: "ProxyCommand ncat must name --proxy host:port"
287
+ };
288
+ const typeAt = words.indexOf("--proxy-type");
289
+ const type = typeAt < 0 ? "http" : words[typeAt + 1] ?? "http";
290
+ if (type === "http") return {
291
+ kind: "proxy",
292
+ proxy: {
293
+ kind: "http",
294
+ ...address
295
+ }
296
+ };
297
+ if (type === "socks5") return {
298
+ kind: "proxy",
299
+ proxy: {
300
+ kind: "socks5",
301
+ ...address
302
+ }
303
+ };
304
+ return {
305
+ kind: "unsupported",
306
+ reason: `ProxyCommand ncat --proxy-type ${type} is not supported`
307
+ };
308
+ }
309
+ return {
310
+ kind: "unsupported",
311
+ reason: `ProxyCommand program ${program === "" ? "(none)" : program} is not supported (only ssh -W, nc -X connect -x and ncat --proxy)`
312
+ };
313
+ }
314
+ /** Buffered reads over one socket, keeping every byte it saw. */
315
+ var Reader = class {
316
+ socket;
317
+ buffer = Buffer.alloc(0);
318
+ waiter;
319
+ ended = false;
320
+ failure;
321
+ /** Bound handlers, kept so `detach` can remove exactly what was added. */
322
+ onData = (chunk) => {
323
+ this.buffer = Buffer.concat([this.buffer, chunk]);
324
+ this.wake();
325
+ };
326
+ onError = (error) => {
327
+ this.failure = error;
328
+ this.wake();
329
+ };
330
+ onClose = () => {
331
+ this.ended = true;
332
+ this.wake();
333
+ };
334
+ constructor(socket) {
335
+ this.socket = socket;
336
+ socket.on("data", this.onData);
337
+ socket.once("error", this.onError);
338
+ socket.once("close", this.onClose);
339
+ }
340
+ wake() {
341
+ const waiter = this.waiter;
342
+ this.waiter = void 0;
343
+ waiter?.();
344
+ }
345
+ /** Wait for more bytes; false when the socket closed or failed. */
346
+ async more() {
347
+ if (this.failure !== void 0) throw this.failure;
348
+ if (this.ended) return;
349
+ await new Promise((resolve) => {
350
+ this.waiter = resolve;
351
+ });
352
+ }
353
+ /** Read until `marker` inclusive (used for the HTTP header block). */
354
+ async until(marker) {
355
+ for (;;) {
356
+ const at = this.buffer.indexOf(marker);
357
+ if (at >= 0) {
358
+ const end = at + marker.length;
359
+ const head = this.buffer.subarray(0, end);
360
+ this.buffer = this.buffer.subarray(end);
361
+ return head;
362
+ }
363
+ await this.more();
364
+ if (this.failure !== void 0) throw this.failure;
365
+ if (this.ended) throw new ProxyError("protocol", "the proxy closed the tunnel before answering");
366
+ }
367
+ }
368
+ /** Read exactly `count` bytes (SOCKS replies). */
369
+ async exact(count) {
370
+ for (;;) {
371
+ if (this.buffer.length >= count) {
372
+ const head = this.buffer.subarray(0, count);
373
+ this.buffer = this.buffer.subarray(count);
374
+ return head;
375
+ }
376
+ await this.more();
377
+ if (this.failure !== void 0) throw this.failure;
378
+ if (this.ended) throw new ProxyError("protocol", "the proxy closed the tunnel before answering");
379
+ }
380
+ }
381
+ /** Push back tunnel bytes that arrived with the handshake reply. */
382
+ release() {
383
+ if (this.buffer.length > 0) {
384
+ const leftover = this.buffer;
385
+ this.buffer = Buffer.alloc(0);
386
+ this.socket.unshift(leftover);
387
+ }
388
+ }
389
+ /**
390
+ * Stop observing the socket after a successful handshake.
391
+ *
392
+ * Without this the `data` listener keeps appending every tunnelled byte to
393
+ * `buffer` for the whole life of the connection — an unbounded leak on an SSH
394
+ * session that moves a few files. The socket belongs to the caller from here on
395
+ * (ssh2 becomes its only reader).
396
+ *
397
+ * Called BEFORE `release()`: an attached `data` listener would immediately
398
+ * consume the pushed-back bytes into `buffer` again, and the handover would lose
399
+ * the SSH banner it just rescued.
400
+ */
401
+ detach() {
402
+ this.socket.off("data", this.onData);
403
+ this.socket.off("error", this.onError);
404
+ this.socket.off("close", this.onClose);
405
+ }
406
+ };
407
+ /** The four octets of a dotted-quad IPv4 literal, or `undefined`. */
408
+ function ipv4Octets(value) {
409
+ const parts = value.split(".");
410
+ if (parts.length !== 4) return void 0;
411
+ const octets = [];
412
+ for (const part of parts) {
413
+ if (!/^\d{1,3}$/.test(part)) return void 0;
414
+ const octet = Number.parseInt(part, 10);
415
+ if (octet > 255) return void 0;
416
+ octets.push(octet);
417
+ }
418
+ return octets;
419
+ }
420
+ /**
421
+ * Expand one IPv6 literal into its eight 16-bit groups, or `undefined`.
422
+ *
423
+ * A SOCKS5 CONNECT carries the target as BYTES, so the literal has to be
424
+ * expanded before it is encoded — and `::` is what makes that non-obvious. The
425
+ * first cut appended a single `'0'` group wherever the text was short, so every
426
+ * compressed form encoded a DIFFERENT address than it names (`2001:db8::1` became
427
+ * `2001:db8:0:0:1:0:0:0`, `::1` became `0:0:0:1:0:0:0:0`): the tunnel opened,
428
+ * nothing errored, and the dial reached a host nobody asked for. Handing back
429
+ * `undefined` for an unexpandable literal is the point — the caller refuses the
430
+ * dial instead of encoding something.
431
+ *
432
+ * Accepted: exactly one `::` anywhere (leading / middle / trailing), eight
433
+ * explicit groups when there is no `::`, and a dotted IPv4 in the LAST group
434
+ * (RFC 4291 §2.2.3, e.g. `::ffff:1.2.3.4`). Two `::`, too many or too few
435
+ * groups, bad hex and a bad quad are all `undefined`, never a guess.
436
+ */
437
+ function expandIPv6(value) {
438
+ const halves = value.split("::");
439
+ if (halves.length > 2) return void 0;
440
+ const compressed = halves.length === 2;
441
+ const readGroups = (part) => {
442
+ if (part === void 0 || part === "") return [];
443
+ const groups = part.split(":");
444
+ const out = [];
445
+ for (let index = 0; index < groups.length; index += 1) {
446
+ const group = groups[index];
447
+ if (group.includes(".")) {
448
+ if (index !== groups.length - 1) return void 0;
449
+ const octets = ipv4Octets(group);
450
+ if (octets === void 0) return void 0;
451
+ const [a = 0, b = 0, c = 0, d = 0] = octets;
452
+ out.push(a << 8 | b, c << 8 | d);
453
+ continue;
454
+ }
455
+ if (!/^[0-9A-Fa-f]{1,4}$/.test(group)) return void 0;
456
+ out.push(Number.parseInt(group, 16));
457
+ }
458
+ return out;
459
+ };
460
+ const head = readGroups(halves[0]);
461
+ const tail = compressed ? readGroups(halves[1]) : [];
462
+ if (head === void 0 || tail === void 0) return void 0;
463
+ const explicit = head.length + tail.length;
464
+ if (!compressed) return explicit === 8 ? head : void 0;
465
+ if (explicit > 7) return void 0;
466
+ return [
467
+ ...head,
468
+ ...Array.from({ length: 8 - explicit }, () => 0),
469
+ ...tail
470
+ ];
471
+ }
472
+ /** Encode one SOCKS5 target address (domain / IPv4 / IPv6). */
473
+ function socksAddress(host, port) {
474
+ const bare = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
475
+ const portBytes = Buffer.alloc(2);
476
+ portBytes.writeUInt16BE(port, 0);
477
+ const octets = ipv4Octets(bare);
478
+ if (octets !== void 0) return Buffer.concat([
479
+ Buffer.from([1]),
480
+ Buffer.from(octets),
481
+ portBytes
482
+ ]);
483
+ if (bare.includes(":")) {
484
+ const groups = expandIPv6(bare);
485
+ if (groups === void 0) throw new ProxyError("target", bare.includes("%") ? `destination ${JSON.stringify(host)} is scoped (link-local); SOCKS5 cannot carry a zone id` : `destination ${JSON.stringify(host)} is not a valid IPv6 address`, "socks5");
486
+ const bytes = groups.flatMap((group) => [group >> 8 & 255, group & 255]);
487
+ return Buffer.concat([
488
+ Buffer.from([4]),
489
+ Buffer.from(bytes),
490
+ portBytes
491
+ ]);
492
+ }
493
+ const name = Buffer.from(bare, "utf8");
494
+ return Buffer.concat([
495
+ Buffer.from([3, name.length]),
496
+ name,
497
+ portBytes
498
+ ]);
499
+ }
500
+ /** One SOCKS5 reply code as an actionable failure. */
501
+ function socksReplyError(code) {
502
+ switch (code) {
503
+ case 2: return new ProxyError("refused", "the proxy does not allow this connection (SOCKS5 rule denied)", "socks5");
504
+ case 3: return new ProxyError("refused", "the proxy cannot reach the network (SOCKS5: network unreachable)", "socks5");
505
+ case 4: return new ProxyError("refused", "the proxy cannot reach the host (SOCKS5: host unreachable)", "socks5");
506
+ case 5: return new ProxyError("refused", "the connection was refused by the target host (via SOCKS5)", "socks5");
507
+ case 6: return new ProxyError("refused", "the connection timed out at the proxy (SOCKS5: TTL expired)", "socks5");
508
+ case 7: return new ProxyError("refused", "the proxy does not support CONNECT (SOCKS5: command not supported)", "socks5");
509
+ case 8: return new ProxyError("protocol", "the proxy does not accept this address type (SOCKS5)", "socks5");
510
+ default: return new ProxyError("refused", `the proxy refused the tunnel (SOCKS5 reply ${code})`, "socks5");
511
+ }
512
+ }
513
+ /**
514
+ * Dial `host:port` through `proxy` and hand back the tunnelled socket.
515
+ *
516
+ * The caller owns the socket (ssh2 takes it as its transport). Everything read
517
+ * past the handshake is pushed back, so the SSH banner is not swallowed.
518
+ *
519
+ * @throws {ProxyError} when the proxy layer — not SSH — is what failed.
520
+ */
521
+ async function openProxySocket(proxy, host, port, options = {}) {
522
+ if (host === "" || !HOST_RE.test(host) || !Number.isInteger(port) || port < 1 || port > 65535) throw new ProxyError("target", `destination must be host:port, got ${JSON.stringify(`${host}:${port}`)}`);
523
+ const budget = options.timeoutMs ?? 8e3;
524
+ const socket = (options.connect ?? ((target, targetPort) => createConnection({
525
+ host: target,
526
+ port: targetPort
527
+ })))(proxy.host, proxy.port);
528
+ const reader = new Reader(socket);
529
+ const timer = setTimeout(() => {
530
+ socket.destroy(new ProxyError("timeout", `the proxy ${proxy.host}:${proxy.port} did not answer within ${budget / 1e3}s`, proxy.kind));
531
+ }, budget);
532
+ timer.unref?.();
533
+ try {
534
+ await new Promise((resolve, reject) => {
535
+ socket.once("connect", () => resolve());
536
+ socket.once("error", (error) => {
537
+ const code = error.code;
538
+ reject(code === "ECONNREFUSED" || code === "EHOSTUNREACH" || code === "ENETUNREACH" || code === "EACCES" || code === "ENOTFOUND" || code === "EAI_AGAIN" || code === "ETIMEDOUT" ? new ProxyError("unreachable", `cannot reach the proxy ${proxy.host}:${proxy.port} (${code ?? error.message})`, proxy.kind) : error);
539
+ });
540
+ });
541
+ if (proxy.kind === "http") await httpTunnel(socket, reader, proxy, host, port);
542
+ else await socks5Tunnel(socket, reader, proxy, host, port);
543
+ reader.detach();
544
+ reader.release();
545
+ return socket;
546
+ } catch (error) {
547
+ try {
548
+ socket.destroy();
549
+ } catch {}
550
+ throw error instanceof ProxyError ? error : new ProxyError("protocol", error instanceof Error ? error.message : String(error), proxy.kind);
551
+ } finally {
552
+ clearTimeout(timer);
553
+ }
554
+ }
555
+ /** HTTP CONNECT: one request line, optional Basic auth, then a 2xx. */
556
+ async function httpTunnel(socket, reader, proxy, host, port) {
557
+ const authority = host.includes(":") && !host.startsWith("[") ? `[${host}]:${port}` : `${host}:${port}`;
558
+ const lines = [`CONNECT ${authority} HTTP/1.1`, `Host: ${authority}`];
559
+ if (proxy.username !== void 0) {
560
+ const token = Buffer.from(`${proxy.username}:${proxy.password ?? ""}`, "utf8").toString("base64");
561
+ lines.push(`Proxy-Authorization: Basic ${token}`);
562
+ }
563
+ socket.write(`${lines.join("\r\n")}\r\n\r\n`);
564
+ const statusLine = (await reader.until("\r\n\r\n")).toString("latin1").split("\r\n")[0] ?? "";
565
+ const match = /^HTTP\/1\.[01] (\d{3})/.exec(statusLine);
566
+ if (match === null) throw new ProxyError("protocol", `the proxy did not answer with HTTP (got ${JSON.stringify(statusLine.slice(0, 60))})`, "http");
567
+ const status = Number.parseInt(match[1] ?? "", 10);
568
+ if (status === 200 || status === 201) return;
569
+ if (status === 407) throw new ProxyError("auth", proxy.username === void 0 ? "the proxy requires a username and password (HTTP 407)" : "the proxy rejected the username and password (HTTP 407)", "http");
570
+ if (status === 403) throw new ProxyError("refused", "the proxy refused this destination (HTTP 403)", "http");
571
+ if (status === 405) throw new ProxyError("refused", "the proxy does not allow CONNECT (HTTP 405)", "http");
572
+ if (status === 502 || status === 503 || status === 504) throw new ProxyError("refused", `the proxy could not reach ${authority} (HTTP ${status})`, "http");
573
+ throw new ProxyError("refused", `the proxy refused the tunnel (HTTP ${status})`, "http");
574
+ }
575
+ /** SOCKS5: greeting, optional user/password, CONNECT, reply. */
576
+ async function socks5Tunnel(socket, reader, proxy, host, port) {
577
+ const wantsAuth = proxy.username !== void 0;
578
+ socket.write(Buffer.from(wantsAuth ? [
579
+ 5,
580
+ 2,
581
+ 0,
582
+ 2
583
+ ] : [
584
+ 5,
585
+ 1,
586
+ 0
587
+ ]));
588
+ const greeting = await reader.exact(2);
589
+ if (greeting[0] !== 5) throw new ProxyError("protocol", "the proxy did not answer SOCKS5 (version byte mismatch)", "socks5");
590
+ const method = greeting[1];
591
+ if (method === 255) throw new ProxyError("auth", wantsAuth ? "the proxy rejected the offered SOCKS5 auth methods" : "the proxy requires SOCKS5 username/password", "socks5");
592
+ if (method === 2) {
593
+ if (proxy.username === void 0) throw new ProxyError("auth", "the proxy requires a SOCKS5 username and password", "socks5");
594
+ const user = Buffer.from(proxy.username, "utf8").subarray(0, 255);
595
+ const pass = Buffer.from(proxy.password ?? "", "utf8").subarray(0, 255);
596
+ socket.write(Buffer.concat([
597
+ Buffer.from([1, user.length]),
598
+ user,
599
+ Buffer.from([pass.length]),
600
+ pass
601
+ ]));
602
+ const reply = await reader.exact(2);
603
+ if (reply[0] !== 1 || reply[1] !== 0) throw new ProxyError("auth", "the proxy rejected the SOCKS5 username and password", "socks5");
604
+ } else if (method !== 0) throw new ProxyError("protocol", `the proxy chose an unknown SOCKS5 auth method (${method})`, "socks5");
605
+ socket.write(Buffer.concat([Buffer.from([
606
+ 5,
607
+ 1,
608
+ 0
609
+ ]), socksAddress(host, port)]));
610
+ const head = await reader.exact(4);
611
+ if (head[0] !== 5) throw new ProxyError("protocol", "the proxy answered SOCKS5 CONNECT with a bad version", "socks5");
612
+ const code = head[1] ?? 0;
613
+ const atyp = head[3];
614
+ const addressBytes = atyp === 1 ? 4 : atyp === 4 ? 16 : atyp === 3 ? (await reader.exact(1))[0] ?? 0 : -1;
615
+ if (addressBytes < 0) throw new ProxyError("protocol", "the proxy answered SOCKS5 with an unknown address type", "socks5");
616
+ await reader.exact(addressBytes + 2);
617
+ if (code !== 0) throw socksReplyError(code);
618
+ }
619
+ //#endregion
14
620
  //#region src/store.ts
15
621
  /**
16
622
  * Durable store for dsh-remote-vs: hosts + workspace bindings in
@@ -25,6 +631,41 @@ function emptyDoc() {
25
631
  tombstones: []
26
632
  };
27
633
  }
634
+ /** The proxy modes a stored host decision may name. */
635
+ const PROXY_MODES = [
636
+ "inherit",
637
+ "direct",
638
+ "proxy",
639
+ "jump"
640
+ ];
641
+ /** Narrow an untrusted value to a declared mode (garbage falls back to `inherit`). */
642
+ function proxyModeOf(mode) {
643
+ return PROXY_MODES.includes(mode) ? mode : "inherit";
644
+ }
645
+ /** Message of an error without assuming it is an `Error`. */
646
+ function messageOf$4(error) {
647
+ return error instanceof Error ? error.message : String(error);
648
+ }
649
+ /**
650
+ * Read a stored default-proxy block, tolerating hand-edited garbage.
651
+ *
652
+ * A malformed value is DROPPED (→ direct) rather than throwing: a store file an
653
+ * older version or a text editor touched must still load, and "direct" is the
654
+ * behaviour an upgrade would have had anyway.
655
+ */
656
+ function sanitizeDefaultProxy(value) {
657
+ if (typeof value !== "object" || value === null) return void 0;
658
+ const raw = value;
659
+ if (raw.proxy === void 0) return { mode: raw.mode === "proxy" ? "proxy" : "direct" };
660
+ try {
661
+ return {
662
+ mode: raw.mode === "proxy" ? "proxy" : "direct",
663
+ proxy: normalizeProxy(raw.proxy)
664
+ };
665
+ } catch {
666
+ return { mode: "direct" };
667
+ }
668
+ }
28
669
  /** Same file identity (both absent counts as same). */
29
670
  function sameStamp$1(left, right) {
30
671
  if (left === null || right === null) return left === right;
@@ -125,7 +766,11 @@ var RemoteStore = class {
125
766
  version: 1,
126
767
  hosts: doc.hosts,
127
768
  workspaces: doc.workspaces,
128
- tombstones: Array.isArray(doc.tombstones) ? doc.tombstones.filter((t) => typeof t === "string") : []
769
+ tombstones: Array.isArray(doc.tombstones) ? doc.tombstones.filter((t) => typeof t === "string") : [],
770
+ ...(() => {
771
+ const defaultProxy = sanitizeDefaultProxy(doc.defaultProxy);
772
+ return defaultProxy === void 0 ? {} : { defaultProxy };
773
+ })()
129
774
  };
130
775
  }
131
776
  save() {
@@ -232,10 +877,15 @@ var RemoteStore = class {
232
877
  port: patch.port ?? current.port,
233
878
  user: patch.user ?? current.user,
234
879
  auth,
880
+ proxy: patch.proxy ?? current.proxy,
235
881
  description: patch.description ?? current.description,
236
882
  tags: patch.tags ?? current.tags
237
883
  };
238
884
  const next = this.normalize(merged, current);
885
+ if (proxyModeOf(next.proxy?.mode) === "jump" && proxyModeOf(current.proxy?.mode) !== "jump") {
886
+ const dependent = this.doc.hosts.find((host) => host.alias !== alias && proxyModeOf(host.proxy?.mode) === "jump" && host.proxy?.jump?.viaAlias === alias);
887
+ if (dependent !== void 0) throw new Error(`host "${dependent.alias}" jumps through this host; change it first`);
888
+ }
239
889
  this.doc.hosts[index] = next;
240
890
  return next;
241
891
  });
@@ -274,6 +924,7 @@ var RemoteStore = class {
274
924
  } else if (typeof auth.password !== "string" || auth.password === "") throw new Error("auth.password must be a non-empty string for password auth");
275
925
  if (payload.description !== void 0 && typeof payload.description !== "string") throw new Error("description must be a string when provided");
276
926
  if (payload.tags !== void 0 && (!Array.isArray(payload.tags) || payload.tags.some((t) => typeof t !== "string"))) throw new Error("tags must be string[] when provided");
927
+ const proxy = payload.proxy === void 0 ? void 0 : this.validateHostProxy(payload.proxy, payload.alias, current);
277
928
  const now = Date.now();
278
929
  return {
279
930
  alias: payload.alias,
@@ -286,6 +937,7 @@ var RemoteStore = class {
286
937
  ...auth.passphrase !== void 0 ? { passphrase: auth.passphrase } : {},
287
938
  ...auth.password !== void 0 ? { password: auth.password } : {}
288
939
  },
940
+ ...proxy === void 0 ? {} : { proxy },
289
941
  ...payload.description !== void 0 ? { description: payload.description } : {},
290
942
  tags: payload.tags ?? [],
291
943
  ...current?.deploy !== void 0 ? { deploy: current.deploy } : {},
@@ -293,6 +945,91 @@ var RemoteStore = class {
293
945
  updatedAt: now
294
946
  };
295
947
  }
948
+ /**
949
+ * Validate one host's stored proxy decision.
950
+ *
951
+ * The rules are the ones the two-level model needs to stay explainable:
952
+ * - the mode is one of the four declared values;
953
+ * - `proxy` needs an endpoint, `jump` needs another EXISTING alias (a host
954
+ * cannot jump through itself, and a chain is impossible to resolve with one
955
+ * pooled hop);
956
+ * - fields that the chosen mode does not use are DROPPED rather than stored, so
957
+ * switching modes cannot leave a stale endpoint behind that a later reader
958
+ * would take for the active one.
959
+ *
960
+ * @returns the normalized setting, or undefined for `inherit` (stored as the
961
+ * field's absence, which is what older files have).
962
+ */
963
+ validateHostProxy(input, alias, current) {
964
+ if (typeof input !== "object" || input === null) throw new Error("proxy must be an object");
965
+ const mode = input.mode;
966
+ if (!PROXY_MODES.includes(mode)) throw new Error("proxy.mode must be inherit, direct, proxy or jump");
967
+ if (mode === "inherit") return void 0;
968
+ if (mode === "direct") return { mode };
969
+ if (mode === "proxy") {
970
+ if (input.proxy === void 0) throw new Error("proxy.mode \"proxy\" requires a proxy endpoint");
971
+ return {
972
+ mode,
973
+ proxy: this.mergeProxyTarget(input.proxy, current?.proxy?.proxy)
974
+ };
975
+ }
976
+ const viaAlias = input.jump?.viaAlias;
977
+ if (typeof viaAlias !== "string" || viaAlias === "") throw new Error("proxy.mode \"jump\" requires proxy.jump.viaAlias");
978
+ if (viaAlias === alias) throw new Error("proxy.jump.viaAlias must name another host, not this one");
979
+ if (!this.doc.hosts.some((host) => host.alias === viaAlias)) throw new Error(`proxy.jump.viaAlias: unknown host alias ${viaAlias}`);
980
+ return {
981
+ mode,
982
+ jump: { viaAlias }
983
+ };
984
+ }
985
+ /**
986
+ * Why a host's proxy decision cannot be used, when it cannot.
987
+ *
988
+ * Reads NEVER throw for this: a host that points at a deleted jump host must
989
+ * still be listed (with the reason on its row) instead of making the whole host
990
+ * list fail. The dial path asks {@link resolveProxy}, which does fail closed.
991
+ */
992
+ proxyProblem(entry, mode) {
993
+ const setting = entry.proxy;
994
+ if (mode === "proxy") {
995
+ if (setting?.proxy === void 0) return "proxy mode is selected but no proxy endpoint is configured";
996
+ try {
997
+ normalizeProxy(setting.proxy);
998
+ return;
999
+ } catch (error) {
1000
+ return messageOf$4(error);
1001
+ }
1002
+ }
1003
+ if (mode !== "jump") return void 0;
1004
+ const viaAlias = setting?.jump?.viaAlias;
1005
+ if (viaAlias === void 0 || viaAlias === "") return "jump mode is selected but no jump host is configured";
1006
+ if (viaAlias === entry.alias) return "a host cannot jump through itself";
1007
+ const via = this.doc.hosts.find((host) => host.alias === viaAlias);
1008
+ if (via === void 0) return `jump host "${viaAlias}" is not configured`;
1009
+ if (proxyModeOf(via.proxy?.mode) === "jump") return `jump host "${viaAlias}" itself uses a jump host (one hop only)`;
1010
+ }
1011
+ /** Secret-free view of one stored proxy endpoint. */
1012
+ targetView(setting) {
1013
+ return {
1014
+ kind: setting.kind,
1015
+ host: setting.host,
1016
+ port: setting.port,
1017
+ ...setting.username === void 0 || setting.username === "" ? {} : { username: setting.username },
1018
+ hasPassword: typeof setting.password === "string" && setting.password !== ""
1019
+ };
1020
+ }
1021
+ /** Secret-free view of one host's proxy decision (always present). */
1022
+ proxyView(entry) {
1023
+ const mode = proxyModeOf(entry.proxy?.mode);
1024
+ const view = { mode };
1025
+ if (entry.proxy?.proxy !== void 0) try {
1026
+ view.target = this.targetView(normalizeProxy(entry.proxy.proxy));
1027
+ } catch {}
1028
+ if (entry.proxy?.jump?.viaAlias !== void 0) view.jumpVia = entry.proxy.jump.viaAlias;
1029
+ const problem = this.proxyProblem(entry, mode);
1030
+ if (problem !== void 0) view.problem = problem;
1031
+ return view;
1032
+ }
296
1033
  /** Secret-free projection for browser/agent surfaces. */
297
1034
  summarize(entry) {
298
1035
  let keyReady = false;
@@ -311,11 +1048,117 @@ var RemoteStore = class {
311
1048
  managedKey: entry.auth.kind === "key" && entry.auth.keyPath !== void 0 && entry.auth.keyPath.startsWith(keysDir() + (process.platform === "win32" ? "\\" : "/")),
312
1049
  ...entry.description !== void 0 ? { description: entry.description } : {},
313
1050
  tags: [...entry.tags],
1051
+ proxy: this.proxyView(entry),
314
1052
  ...entry.deploy !== void 0 ? { deploy: entry.deploy } : {},
315
1053
  createdAt: entry.createdAt,
316
1054
  updatedAt: entry.updatedAt
317
1055
  };
318
1056
  }
1057
+ /** Secret-free view of the profile-wide proxy default (read-only). */
1058
+ getDefaultProxy() {
1059
+ this.reload();
1060
+ return this.defaultProxyView();
1061
+ }
1062
+ /** View of the in-memory document (no reload: callers already reloaded). */
1063
+ defaultProxyView() {
1064
+ const stored = this.doc.defaultProxy;
1065
+ const view = { defaultMode: stored?.mode === "proxy" ? "proxy" : "direct" };
1066
+ if (stored?.proxy !== void 0) try {
1067
+ view.target = this.targetView(normalizeProxy(stored.proxy));
1068
+ } catch {
1069
+ view.defaultMode = "direct";
1070
+ }
1071
+ else if (view.defaultMode === "proxy") view.defaultMode = "direct";
1072
+ return view;
1073
+ }
1074
+ /**
1075
+ * Patch the profile-wide proxy default.
1076
+ *
1077
+ * `target` semantics follow the host form: omitted keeps the stored endpoint,
1078
+ * `null` clears it, an object replaces it — and an EMPTY PASSWORD keeps the
1079
+ * stored one, because the browser never receives secrets back.
1080
+ */
1081
+ patchDefaultProxy(patch) {
1082
+ if (typeof patch !== "object" || patch === null) throw new Error("proxy settings patch must be an object");
1083
+ return this.mutate(() => {
1084
+ const current = this.doc.defaultProxy ?? { mode: "direct" };
1085
+ let proxy = current.proxy;
1086
+ if (patch.target === null) proxy = void 0;
1087
+ else if (patch.target !== void 0) proxy = this.mergeProxyTarget(patch.target, current.proxy);
1088
+ const mode = patch.defaultMode ?? current.mode;
1089
+ if (mode !== "direct" && mode !== "proxy") throw new Error("defaultMode must be 'direct' or 'proxy'");
1090
+ if (mode === "proxy" && proxy === void 0) throw new Error("defaultMode \"proxy\" requires a proxy target");
1091
+ this.doc.defaultProxy = {
1092
+ mode,
1093
+ ...proxy === void 0 ? {} : { proxy }
1094
+ };
1095
+ return this.defaultProxyView();
1096
+ });
1097
+ }
1098
+ /**
1099
+ * Normalize a patched endpoint, keeping the stored password on an empty one.
1100
+ *
1101
+ * "Empty means keep" is only sound for the SAME endpoint: the browser never
1102
+ * receives the secret back, so every PATCH of a proxied host arrives without
1103
+ * one — but when kind/host/port/username changed, the stored password is a
1104
+ * credential for a DIFFERENT server, and carrying it over would send the old
1105
+ * secret to a new address (a 407 at best, a leaked credential at worst). A
1106
+ * changed endpoint therefore drops it and the user re-enters it.
1107
+ */
1108
+ mergeProxyTarget(target, current) {
1109
+ const next = normalizeProxy(target);
1110
+ if ((typeof target.password === "string" ? target.password : "") === "") if (current !== void 0 && current.kind === next.kind && current.host === next.host && current.port === next.port && (current.username ?? "") === (next.username ?? "") && current.password !== void 0) next.password = current.password;
1111
+ else delete next.password;
1112
+ return next;
1113
+ }
1114
+ /**
1115
+ * Resolve one host's EFFECTIVE route, in the precedence the UI describes:
1116
+ * the host's own decision, else the profile default, else direct.
1117
+ *
1118
+ * Unlike {@link summarize}, this FAILS CLOSED for an unusable jump: dialing
1119
+ * through a deleted host (or a second jump) cannot work, and the caller must say
1120
+ * why instead of silently connecting some other way.
1121
+ */
1122
+ resolveProxy(alias) {
1123
+ const entry = this.require(alias);
1124
+ const mode = proxyModeOf(entry.proxy?.mode);
1125
+ if (mode === "direct") return { kind: "direct" };
1126
+ if (mode === "proxy") {
1127
+ const stored = entry.proxy?.proxy;
1128
+ if (stored === void 0) throw new Error(`host ${alias}: proxy mode is selected but no proxy endpoint is configured`);
1129
+ return {
1130
+ kind: "proxy",
1131
+ proxy: this.requireStoredProxy(stored, alias),
1132
+ source: "host"
1133
+ };
1134
+ }
1135
+ if (mode === "jump") {
1136
+ const viaAlias = entry.proxy?.jump?.viaAlias;
1137
+ if (viaAlias === void 0 || viaAlias === "") throw new Error(`host ${alias}: jump mode is selected but no jump host is configured`);
1138
+ if (viaAlias === alias) throw new Error(`host ${alias}: a host cannot jump through itself`);
1139
+ const via = this.get(viaAlias);
1140
+ if (via === void 0) throw new Error(`host ${alias}: jump host "${viaAlias}" is not configured`);
1141
+ if (proxyModeOf(via.proxy?.mode) === "jump") throw new Error(`host ${alias}: jump host "${viaAlias}" itself uses a jump host (one hop only)`);
1142
+ return {
1143
+ kind: "jump",
1144
+ viaAlias
1145
+ };
1146
+ }
1147
+ const storedDefault = this.doc.defaultProxy;
1148
+ if (storedDefault?.mode === "proxy" && storedDefault.proxy !== void 0) return {
1149
+ kind: "proxy",
1150
+ proxy: this.requireStoredProxy(storedDefault.proxy, alias),
1151
+ source: "default"
1152
+ };
1153
+ return { kind: "direct" };
1154
+ }
1155
+ requireStoredProxy(stored, alias) {
1156
+ try {
1157
+ return normalizeProxy(stored);
1158
+ } catch (error) {
1159
+ throw new Error(`host ${alias}: invalid proxy configuration (${messageOf$4(error)})`);
1160
+ }
1161
+ }
319
1162
  setDeploy(alias, state) {
320
1163
  this.mutate(() => {
321
1164
  const entry = this.doc.hosts.find((h) => h.alias === alias);
@@ -408,6 +1251,10 @@ const REMOTE_API = {
408
1251
  routing: "/api/dsh-remote/routing",
409
1252
  /** Client view preferences (auto-open the remote page + its width share). */
410
1253
  viewSettings: "/api/dsh-remote/view-settings",
1254
+ /** Profile-wide proxy default (per-host overrides live on the host rows). */
1255
+ proxySettings: "/api/dsh-remote/proxy-settings",
1256
+ /** Live SSH pool shape per host: connections, channels, slot occupancy. */
1257
+ connections: "/api/dsh-remote/connections",
411
1258
  /** Current working directory of one live session (click resolution helper). */
412
1259
  sessionCwd: "/api/dsh-remote/session-cwd",
413
1260
  /** What one live session changed on its remote host (the review panel). */
@@ -591,6 +1438,58 @@ var import_lib = require_lib();
591
1438
  /** Idle time after which a pooled connection is closed. */
592
1439
  const IDLE_MS = 1800 * 1e3;
593
1440
  /**
1441
+ * How long a port forward waits for its DEDICATED connection before falling back.
1442
+ *
1443
+ * The dedicated connection is an optimization, so it must never become the reason
1444
+ * a local socket waits: a server that silently DROPS the extra connection (a very
1445
+ * common `MaxStartups` symptom) would otherwise cost the whole connect watchdog
1446
+ * (45s) per forward channel, with the user staring at a hanging page. Three
1447
+ * seconds is plenty for a second handshake to a host that is already reachable
1448
+ * (the shared connection is up by definition); past that, use the shared one and
1449
+ * let the abandoned dial finish in the background.
1450
+ *
1451
+ * Override with DSH_REMOTE_VS_FORWARD_BUDGET_MS (milliseconds, >= 10) so the gate
1452
+ * does not spend three seconds per case.
1453
+ */
1454
+ const FORWARD_DEDICATED_BUDGET_MS = (() => {
1455
+ const raw = Number(process.env.DSH_REMOTE_VS_FORWARD_BUDGET_MS);
1456
+ return Number.isFinite(raw) && raw >= 10 ? raw : 3e3;
1457
+ })();
1458
+ /**
1459
+ * How long a refused/timed-out dedicated forward connection is skipped per alias.
1460
+ *
1461
+ * A browser opens several forward channels per page; retrying the same refused
1462
+ * handshake for every one of them is exactly the waiting we just removed. One
1463
+ * minute covers the burst; `drop(alias)` (host edited/deleted) and a successful
1464
+ * dedicated connection clear it immediately.
1465
+ */
1466
+ const FORWARD_DEDICATED_BLOCK_MS = 6e4;
1467
+ /**
1468
+ * How long a file operation waits for its DEDICATED SFTP connection before
1469
+ * falling back to the shared one.
1470
+ *
1471
+ * Same argument as {@link FORWARD_DEDICATED_BUDGET_MS}, and it binds harder
1472
+ * here: browsing fires one request per folder open (plus a stat per entry), so a
1473
+ * server that silently DROPS the extra connection would otherwise stall the
1474
+ * explorer for the whole connect watchdog on EVERY click. The dedicated
1475
+ * connection is an optimization; it must never be what the user waits on.
1476
+ *
1477
+ * Override with DSH_REMOTE_VS_SFTP_BUDGET_MS (milliseconds, >= 10).
1478
+ */
1479
+ const SFTP_DEDICATED_BUDGET_MS = (() => {
1480
+ const raw = Number(process.env.DSH_REMOTE_VS_SFTP_BUDGET_MS);
1481
+ return Number.isFinite(raw) && raw >= 10 ? raw : 3e3;
1482
+ })();
1483
+ /**
1484
+ * How long a refused dedicated SFTP connection is skipped per alias.
1485
+ *
1486
+ * Without it the fallback would be re-dialed by every browse request — the exact
1487
+ * waiting the dedicated budget above just removed. One minute covers a burst of
1488
+ * browsing; `drop(alias)` (host edited/deleted) and a successful dedicated
1489
+ * connection clear it immediately.
1490
+ */
1491
+ const SFTP_DEDICATED_BLOCK_MS = 6e4;
1492
+ /**
594
1493
  * Connection establishment timeout, including authentication.
595
1494
  *
596
1495
  * This was 15s, which is not a handshake budget so much as a CPU budget: on a
@@ -659,20 +1558,116 @@ const CONTROL_TIMEOUT_MS = 15e3;
659
1558
  */
660
1559
  const GROUP_KILL_GRACE_MS = 3e3;
661
1560
  /**
662
- * Concurrent channels the pool opens per alias. The server's own `MaxSessions`
663
- * (10 on the hosts this was measured against) is the real ceiling, and running
664
- * past it fails the extra channels hard — "open failed / administratively
665
- * prohibited" — with nobody retrying. Six is chosen to leave room for what is
666
- * deliberately NOT counted here: PTY terminals, the processes the subprocess
667
- * runtime owns, and the helper's channel.
1561
+ * Concurrent EXEC channels the pool opens per alias on the SHARED connection.
1562
+ *
1563
+ * The server's own `MaxSessions` (10 on the hosts this was measured against) is
1564
+ * the real ceiling, and a channel past it is refused HARD — ssh2 reports
1565
+ * "administratively prohibited" and nobody retries, so the operation fails in a
1566
+ * way that looks like a broken host. Queueing is the readable alternative, which
1567
+ * is why every counted channel kind goes through a budget instead.
1568
+ *
1569
+ * The counting is now honest — every `conn.exec` channel takes a slot:
1570
+ * - `runExec` (every ordinary command) and `execChannel` (the subprocess
1571
+ * runtime's long-lived channels, see `p2/ssh-proc.ts`), both on this budget;
1572
+ * - network verbs ({@link NET_CHANNEL_LIMIT}) and git commands
1573
+ * ({@link GIT_CHANNEL_LIMIT}), on their own budgets on the same connection.
1574
+ * PTY terminals, port forwards and SFTP sessions ride their OWN connections, so
1575
+ * they cannot exhaust this allowance at all.
1576
+ *
1577
+ * **The arithmetic (shared connection, measured `MaxSessions` 10)**:
1578
+ * counted channels are exec 4 + network 2 + git 3 = **9**. The tenth session is
1579
+ * deliberately left free for the only channels that are still NOT counted: the
1580
+ * pool's own housekeeping (`bare` — the one-shot `setsid` capability probe and
1581
+ * the group kill). Those are transient, but they must never be refused, because
1582
+ * a refused probe silently degrades the timeout path and a refused kill leaks a
1583
+ * remote process. So 9 + 1 is a BOUNDED DESIGN, not spare headroom: a tenth
1584
+ * counted channel would put the sum at 10 only as long as nothing transient ever
1585
+ * fires — an assumption the pool cannot make.
1586
+ *
1587
+ * **Why 4 and not more** — this is a deliberate split of the same nine, not a
1588
+ * reduction of it. The field call: "several workspaces / repositories scanning at
1589
+ * once" is the common shape, while "an agent running many exec commands at once"
1590
+ * is rarer, so one slot moved from exec to the git lane (git 2 → 3) and the
1591
+ * network lane stayed at two (push and pull must not serialize). The known cost:
1592
+ * exec concurrency drops from five to four, so an agent's background commands plus
1593
+ * a monitor sample plus the process panel plus the listening-port enumeration can
1594
+ * fill it and the fifth waits — bounded at 30 s with a readable message, and
1595
+ * visible as `Shared 4/4 · N queued` in the monitor. If exec turns out to be the
1596
+ * real bottleneck, move the slot back; the total must stay 9.
1597
+ *
1598
+ * The budget is PER CONNECTION, and the pool holds up to four connections per
1599
+ * alias, so the other classes (PTY/forward/SFTP) keep their own ceilings.
1600
+ */
1601
+ const CHANNEL_LIMIT = 4;
1602
+ /**
1603
+ * Concurrent SFTP sessions on the DEDICATED file connection.
1604
+ *
1605
+ * Deliberately its own number rather than {@link CHANNEL_LIMIT}: the shared
1606
+ * connection's ceiling is tight because three budgets share it with the transient
1607
+ * `bare` probe/kill, while the file connection carries nothing but SFTP sessions
1608
+ * and has the whole `MaxSessions` (10) to itself. Six is what the transfer
1609
+ * measurement landed on (the extra channel windows a download may open), and it is
1610
+ * unchanged by the exec/network/git rebalance.
1611
+ */
1612
+ const SFTP_CHANNEL_LIMIT = 6;
1613
+ /**
1614
+ * Concurrent NETWORK verbs (`git fetch` / `pull` / `push` / `sync`) per alias.
1615
+ *
1616
+ * They ride the SHARED connection (no fifth link: the traffic is not the problem,
1617
+ * the HOLD TIME is) but get their own budget, because their timeout is measured
1618
+ * in minutes — 20 by default. On the exec budget one stuck push pinned one of the
1619
+ * exec slots for the whole budget, and a couple of them filled the table: status
1620
+ * refreshes, the process panel, the monitor and every agent tool then queued 30 s
1621
+ * and failed with "host is busy". With a separate table that can no longer happen.
1622
+ *
1623
+ * Two is enough for the real concurrency (a push and a pull side by side; `sync`
1624
+ * runs its steps sequentially). A third verb waits, and says so in its own words
1625
+ * (see `budgetOf`). The full per-connection arithmetic lives on
1626
+ * {@link CHANNEL_LIMIT}: exec 4 + network 2 + git 3 = 9 counted, with one session
1627
+ * left free for the transient `bare` probe/kill.
1628
+ */
1629
+ const NET_CHANNEL_LIMIT = 2;
1630
+ /**
1631
+ * Concurrent GIT commands (`git status` / `diff` / `log` reads AND the local
1632
+ * writes — commit, stage, discard, branch create/rename/delete, merge) per alias.
1633
+ *
1634
+ * Same argument as the network lane, from the other end of the timeout scale: a
1635
+ * big repository's `git status` alone is allowed 300 s by default
1636
+ * (`DEFAULT_GIT_TIMEOUT_MS`, up to 30 minutes), and every git command used to
1637
+ * hold one of the exec slots for its whole run — while the monitor, the process
1638
+ * panel, the ledger's own next scan and every agent tool queued behind it and
1639
+ * answered "host is busy" after 30 s.
1640
+ *
1641
+ * NOTE the lane is "git commands", not "repository reads": the SCM panel sends its
1642
+ * local writes (`git commit`, `git add`, `git restore`, branch verbs) here too,
1643
+ * because they are git commands with a git timeout. They are fast, and they no
1644
+ * longer occupy a slot out of the same few the monitor and the agent tools use.
1645
+ *
1646
+ * **Why three** (shared connection, measured `MaxSessions` 10):
1647
+ * - counted channels: exec 4 + network 2 + git 3 = 9, plus the one session kept
1648
+ * free for the transient `bare` probe/kill — see {@link CHANNEL_LIMIT};
1649
+ * - three covers the load the field actually shows: several open workspaces or
1650
+ * repositories scanning at once (each runs a tracked status AND, outside the
1651
+ * client queue, an untracked walk), which is more common than an agent running
1652
+ * many commands at the same instant — hence the extra slot came out of exec;
1653
+ * - four would make 10 counted with the probe reserve gone; the surplus channel
1654
+ * past `MaxSessions` is refused HARD by sshd ("administratively prohibited", no
1655
+ * retry) — the exact failure these budgets exist to replace with a bounded
1656
+ * queue. Raising this further means taking the slot from exec again.
668
1657
  */
669
- const CHANNEL_LIMIT = 6;
1658
+ const GIT_CHANNEL_LIMIT = 3;
670
1659
  /**
671
1660
  * How long an operation waits for a channel slot before failing. Bounded on
672
1661
  * purpose: queueing forever behind a peer that never finishes is worse than a
673
1662
  * readable error that tells the user to retry.
1663
+ *
1664
+ * Override with DSH_REMOTE_VS_CHANNEL_WAIT_MS (milliseconds, >= 10) so a gate can
1665
+ * assert the "busy" message without waiting the production 30 s.
674
1666
  */
675
- const CHANNEL_WAIT_MS = 3e4;
1667
+ const CHANNEL_WAIT_MS = (() => {
1668
+ const raw = Number(process.env.DSH_REMOTE_VS_CHANNEL_WAIT_MS);
1669
+ return Number.isFinite(raw) && raw >= 10 ? raw : 3e4;
1670
+ })();
676
1671
  /**
677
1672
  * Idle time after which the shared BROWSE SFTP session is closed.
678
1673
  *
@@ -721,12 +1716,94 @@ var RemotePool = class {
721
1716
  * that refuses extra connections still gets a working terminal.
722
1717
  */
723
1718
  shellConns = /* @__PURE__ */ new Map();
1719
+ /**
1720
+ * Dedicated connections for `ssh -L` port forwards (one per alias).
1721
+ *
1722
+ * The other half of the same argument: a forwarded channel carries arbitrary
1723
+ * TCP (a database, an SSH tunnel, a whole browser page), so it is long-lived
1724
+ * and can move a lot of data. Multiplexed onto the shared connection it would
1725
+ * queue ahead of exec/SFTP channels (SSH has no per-channel priority), and a
1726
+ * remote service that stalls would hold the window `git status` needs. A
1727
+ * terminal already gets its own connection (`shellConns`); forward traffic gets
1728
+ * its own for exactly the same reason.
1729
+ *
1730
+ * Cost: one extra handshake per alias that actually receives a forwarded
1731
+ * connection, plus one held TCP connection while any of its forward channels is
1732
+ * open (the 30-minute idle eviction applies once the last one closes).
1733
+ * `forwardOut` falls back to the shared connection when this one cannot be
1734
+ * established (e.g. the server refuses extra connections), so a forward never
1735
+ * stops working because of it — it only loses the isolation.
1736
+ */
1737
+ forwardConns = /* @__PURE__ */ new Map();
1738
+ /**
1739
+ * Dedicated connections for FILE operations (one per alias).
1740
+ *
1741
+ * The third instance of the same argument. Browse/read/write/upload/download
1742
+ * used to ride the shared connection, which meant a `git status` burst or a
1743
+ * long exec could sit in front of a directory refresh (SSH offers no
1744
+ * per-channel priority), AND that the shared link's channel budget was shared
1745
+ * with file I/O: a few in-flight git/search commands and the explorer could not
1746
+ * open a channel at all. A file operation is exactly the traffic a user is
1747
+ * watching (a folder must open, a save must land), so it gets its own
1748
+ * connection and its own channel budget (`sftpSlots`).
1749
+ *
1750
+ * Cost: one extra handshake per alias that touches files, plus one held TCP
1751
+ * connection while any of its channels is open (the 30-minute idle eviction
1752
+ * applies once the last one ends). `acquireSftp` falls back to the
1753
+ * shared connection when this one cannot be established — a host that refuses
1754
+ * extra connections still serves files, it only loses the isolation.
1755
+ */
1756
+ sftpConns = /* @__PURE__ */ new Map();
1757
+ /** Aliases whose dedicated-SFTP downgrade was already logged (once per alias). */
1758
+ sftpFallbackNoted = /* @__PURE__ */ new Set();
1759
+ /** alias -> timestamp until which the dedicated SFTP connection is skipped. */
1760
+ sftpBlocked = /* @__PURE__ */ new Map();
1761
+ /**
1762
+ * Aliases whose file operations are DOWNGRADED right now (sticky until a
1763
+ * dedicated connection succeeds again or the host is edited).
1764
+ *
1765
+ * Purely diagnostic: `stats()` reports it so the monitor page can say "these
1766
+ * files are riding the shared connection" instead of leaving the user to
1767
+ * wonder why a browse refresh still queues behind git.
1768
+ */
1769
+ sftpFallback = /* @__PURE__ */ new Set();
1770
+ /** Aliases whose dedicated-forward downgrade was already logged (once per alias). */
1771
+ forwardFallbackNoted = /* @__PURE__ */ new Set();
1772
+ /** alias -> timestamp until which the dedicated forward connection is skipped. */
1773
+ forwardBlocked = /* @__PURE__ */ new Map();
724
1774
  /** TOFU fingerprints observed this process (alias -> sha256). */
725
1775
  hostKeys = /* @__PURE__ */ new Map();
726
1776
  /** Per-alias `setsid --wait` capability, probed once (see supportsSetsid). */
727
1777
  setsidProbes = /* @__PURE__ */ new Map();
728
- /** Per-alias channel slots and the queue waiting for one (see acquireSlot). */
1778
+ /**
1779
+ * Channel slots of the SHARED connection (see acquireSlot), and of the
1780
+ * dedicated SFTP connection.
1781
+ *
1782
+ * Two tables because the budget is per connection (`MaxSessions` counts
1783
+ * channels on one link): a fallback SFTP operation counts against the shared
1784
+ * table — the connection it really rides — and never against both.
1785
+ */
729
1786
  slots = /* @__PURE__ */ new Map();
1787
+ sftpSlots = /* @__PURE__ */ new Map();
1788
+ /**
1789
+ * Channel budget of the NETWORK verbs (see {@link NET_CHANNEL_LIMIT}).
1790
+ *
1791
+ * A third table on the SHARED connection: unlike the SFTP lane this is not about
1792
+ * isolating bytes, it is about isolating TIME. A `git push` holds its channel
1793
+ * for minutes, and the failure mode it caused — a full exec table, so every
1794
+ * status refresh answered "host is busy" after 30 s — came from the two kinds
1795
+ * sharing one ceiling.
1796
+ */
1797
+ netSlots = /* @__PURE__ */ new Map();
1798
+ /**
1799
+ * Channel budget of the GIT COMMANDS (see {@link GIT_CHANNEL_LIMIT}).
1800
+ *
1801
+ * A fourth table on the SHARED connection, for the same reason as the network
1802
+ * one — hold TIME, not traffic: a `git status` on a big tree may run for
1803
+ * minutes, and a git command must not be the reason a monitor sample or an agent
1804
+ * tool waits.
1805
+ */
1806
+ gitSlots = /* @__PURE__ */ new Map();
730
1807
  /** Per-alias BROWSE SFTP session (see withBrowseSftp). */
731
1808
  browsed = /* @__PURE__ */ new Map();
732
1809
  /** Per-alias connection health for the browser's status chip (see status). */
@@ -740,10 +1817,25 @@ var RemotePool = class {
740
1817
  this.setsidProbes.delete(alias);
741
1818
  this.evictFrom(this.conns, alias);
742
1819
  this.evictFrom(this.shellConns, alias);
1820
+ this.evictFrom(this.forwardConns, alias);
1821
+ this.evictFrom(this.sftpConns, alias);
1822
+ this.forwardBlocked.delete(alias);
1823
+ this.forwardFallbackNoted.delete(alias);
1824
+ this.sftpBlocked.delete(alias);
1825
+ this.sftpFallbackNoted.delete(alias);
1826
+ this.sftpFallback.delete(alias);
1827
+ this.sftpSlots.delete(alias);
1828
+ this.netSlots.delete(alias);
1829
+ this.gitSlots.delete(alias);
743
1830
  }
744
1831
  /** Close every pooled connection. */
745
1832
  dispose() {
746
- for (const alias of /* @__PURE__ */ new Set([...this.conns.keys(), ...this.shellConns.keys()])) this.drop(alias);
1833
+ for (const alias of /* @__PURE__ */ new Set([
1834
+ ...this.conns.keys(),
1835
+ ...this.shellConns.keys(),
1836
+ ...this.forwardConns.keys(),
1837
+ ...this.sftpConns.keys()
1838
+ ])) this.drop(alias);
747
1839
  }
748
1840
  /**
749
1841
  * Forget one alias's connection HEALTH (host edited/removed), not just its
@@ -765,22 +1857,131 @@ var RemotePool = class {
765
1857
  */
766
1858
  status() {
767
1859
  const aliases = /* @__PURE__ */ new Set([...this.conns.keys(), ...this.health.keys()]);
1860
+ /** The host rows, read ONCE for the whole answer (see `configuredEgress`). */
1861
+ const hosts = /* @__PURE__ */ new Map();
768
1862
  try {
769
- for (const host of this.store.list()) aliases.add(host.alias);
1863
+ for (const host of this.store.list()) {
1864
+ aliases.add(host.alias);
1865
+ hosts.set(host.alias, host);
1866
+ }
770
1867
  } catch {}
771
1868
  return [...aliases].sort().map((alias) => {
772
1869
  const entry = this.health.get(alias);
773
1870
  const pooled = this.conns.get(alias);
1871
+ const egress = this.liveEgress(alias);
1872
+ const configured = egress === void 0 ? this.configuredEgress(alias, hosts.get(alias)) : void 0;
774
1873
  return {
775
1874
  alias,
776
1875
  state: entry?.state ?? "idle",
777
- open: pooled !== void 0 && pooled.connecting === void 0 || this.shellConns.get(alias)?.connecting === void 0 && this.shellConns.has(alias),
1876
+ open: pooled !== void 0 && pooled.connecting === void 0 || this.shellConns.get(alias)?.connecting === void 0 && this.shellConns.has(alias) || this.forwardConns.get(alias)?.connecting === void 0 && this.forwardConns.has(alias) || this.sftpConns.get(alias)?.connecting === void 0 && this.sftpConns.has(alias),
778
1877
  ...entry?.okAt === void 0 ? {} : { okAt: entry.okAt },
779
1878
  ...entry?.errorAt === void 0 ? {} : { errorAt: entry.errorAt },
780
- ...entry?.error === void 0 ? {} : { error: entry.error }
1879
+ ...entry?.error === void 0 ? {} : { error: entry.error },
1880
+ ...egress === void 0 ? {} : { egress },
1881
+ ...configured === void 0 ? {} : { configured }
781
1882
  };
782
1883
  });
783
1884
  }
1885
+ /**
1886
+ * Live pool shape per host: connections, channels, and channel-budget
1887
+ * occupancy (see `RemoteHostPoolStats`).
1888
+ *
1889
+ * Same contract as `status()`: read-only and dial-free, so the monitor's poll
1890
+ * reports what the pool already knows instead of creating work. Answers every
1891
+ * alias the store knows PLUS every alias the pool holds something for — a host
1892
+ * removed from the store still has a connection for a moment, and a page that
1893
+ * shows connections must not hide exactly those.
1894
+ */
1895
+ stats() {
1896
+ const aliases = /* @__PURE__ */ new Set([
1897
+ ...this.conns.keys(),
1898
+ ...this.shellConns.keys(),
1899
+ ...this.forwardConns.keys(),
1900
+ ...this.sftpConns.keys(),
1901
+ ...this.health.keys()
1902
+ ]);
1903
+ try {
1904
+ for (const host of this.store.list()) aliases.add(host.alias);
1905
+ } catch {}
1906
+ return [...aliases].sort().map((alias) => {
1907
+ const shared = this.conns.get(alias);
1908
+ const sharedOpen = shared !== void 0 && shared.connecting === void 0;
1909
+ return {
1910
+ alias,
1911
+ connections: {
1912
+ shared: this.laneOf(this.conns, alias),
1913
+ pty: this.laneOf(this.shellConns, alias),
1914
+ forward: this.laneOf(this.forwardConns, alias),
1915
+ sftp: this.laneOf(this.sftpConns, alias)
1916
+ },
1917
+ slots: this.slotsOf(this.slots.get(alias)),
1918
+ ...this.sftpSlots.has(alias) ? { sftpSlots: this.slotsOf(this.sftpSlots.get(alias), SFTP_CHANNEL_LIMIT) } : {},
1919
+ ...this.netSlots.has(alias) ? { netSlots: this.slotsOf(this.netSlots.get(alias), NET_CHANNEL_LIMIT) } : {},
1920
+ ...this.gitSlots.has(alias) ? { gitSlots: this.slotsOf(this.gitSlots.get(alias), GIT_CHANNEL_LIMIT) } : {},
1921
+ ...sharedOpen && shared.egress !== void 0 ? { egress: shared.egress } : {},
1922
+ ...this.sftpFallback.has(alias) ? { sftpFallback: true } : {}
1923
+ };
1924
+ });
1925
+ }
1926
+ /** One lane of one host: dialed or not, its open channels, its pinned rounds. */
1927
+ laneOf(map, alias) {
1928
+ const pooled = map.get(alias);
1929
+ if (pooled === void 0) return {
1930
+ open: false,
1931
+ channels: 0,
1932
+ held: 0
1933
+ };
1934
+ return {
1935
+ open: pooled.connecting === void 0,
1936
+ channels: pooled.channels ?? 0,
1937
+ held: pooled.held
1938
+ };
1939
+ }
1940
+ /** One channel budget, as reported (a budget nobody touched is empty, not absent). */
1941
+ slotsOf(state, limit = CHANNEL_LIMIT) {
1942
+ return {
1943
+ active: state?.active ?? 0,
1944
+ queued: state?.queue.length ?? 0,
1945
+ limit
1946
+ };
1947
+ }
1948
+ /**
1949
+ * The egress of the alias' LIVE connection, whichever class owns it.
1950
+ *
1951
+ * All four classes open through the same resolved route, so the first one that
1952
+ * is up answers for the alias; the shared connection is preferred because it is
1953
+ * the one exec/browse (the surface the chip describes) rides.
1954
+ */
1955
+ liveEgress(alias) {
1956
+ for (const map of [
1957
+ this.conns,
1958
+ this.forwardConns,
1959
+ this.shellConns,
1960
+ this.sftpConns
1961
+ ]) {
1962
+ const pooled = map.get(alias);
1963
+ if (pooled === void 0 || pooled.connecting !== void 0) continue;
1964
+ if (pooled.egress !== void 0) return pooled.egress;
1965
+ }
1966
+ }
1967
+ /**
1968
+ * The route the stored configuration resolves to, for an alias with NO live
1969
+ * connection. Pure observation, and absorbed: a dangling jump chain or a
1970
+ * half-configured proxy makes `resolveProxy` throw, and a status poll must
1971
+ * answer "the stored route is broken, here is why" instead of failing — the
1972
+ * chip still has to render, and a 500 would hide the reason it exists to show.
1973
+ */
1974
+ configuredEgress(alias, host) {
1975
+ if (host === void 0) return void 0;
1976
+ try {
1977
+ return egressOf(this.store.resolveProxy(alias), host);
1978
+ } catch (error) {
1979
+ return {
1980
+ ...storedEgress(host),
1981
+ problem: messageOf$3(error)
1982
+ };
1983
+ }
1984
+ }
784
1985
  /** Record a successful dial or transport-level operation. */
785
1986
  markOk(alias) {
786
1987
  this.health.set(alias, {
@@ -867,12 +2068,18 @@ var RemotePool = class {
867
2068
  * of queueing. The pool's own housekeeping (`bare`: the setsid probe and the
868
2069
  * group kill) is exempt — a kill that waits behind user traffic would be a
869
2070
  * worse bug than the one it fixes.
2071
+ *
2072
+ * `opts.lane` picks the budget: network verbs (`git fetch/pull/push/sync`) have
2073
+ * their own small one, so a 20-minute push cannot starve the exec slots.
2074
+ * Acquisition and release read the SAME table — a mismatch would leak a slot on
2075
+ * one budget and double-count on the other.
870
2076
  */
871
2077
  async exec(alias, command, opts = {}) {
872
2078
  if (opts.bare === true) return this.runExec(alias, command, opts);
873
2079
  const started = Date.now();
2080
+ const slots = this.execBudget(opts.lane);
874
2081
  try {
875
- await this.acquireSlot(alias);
2082
+ await this.acquireSlot(alias, slots);
876
2083
  } catch (error) {
877
2084
  return {
878
2085
  success: false,
@@ -890,9 +2097,15 @@ var RemotePool = class {
890
2097
  else if (result.success || result.exitCode !== null) this.markOk(alias);
891
2098
  return result;
892
2099
  } finally {
893
- this.releaseSlot(alias);
2100
+ this.releaseSlot(alias, slots);
894
2101
  }
895
2102
  }
2103
+ /** The channel budget an exec spends, by lane (see `ExecOptions.lane`). */
2104
+ execBudget(lane) {
2105
+ if (lane === "network") return this.netSlots;
2106
+ if (lane === "git") return this.gitSlots;
2107
+ return this.slots;
2108
+ }
896
2109
  /** The exec body, run while the caller already holds a channel slot. */
897
2110
  async runExec(alias, command, opts = {}) {
898
2111
  const started = Date.now();
@@ -1029,6 +2242,7 @@ var RemotePool = class {
1029
2242
  } catch {}
1030
2243
  }, GROUP_KILL_GRACE_MS).unref?.();
1031
2244
  else stream = channel;
2245
+ this.countChannel(this.conns, alias, channel);
1032
2246
  channel.on("close", (code, signalName) => {
1033
2247
  if (code !== null && code !== void 0 || signalName !== null && signalName !== void 0) exited = true;
1034
2248
  if (timedOut && session && pgid === void 0) warnOnce();
@@ -1138,6 +2352,7 @@ var RemotePool = class {
1138
2352
  if (dedicated) this.releaseIn(this.shellConns, alias);
1139
2353
  else this.release(alias);
1140
2354
  });
2355
+ this.countChannel(dedicated ? this.shellConns : this.conns, alias, channel);
1141
2356
  this.markOk(alias);
1142
2357
  return channel;
1143
2358
  } catch (error) {
@@ -1147,10 +2362,37 @@ var RemotePool = class {
1147
2362
  throw error;
1148
2363
  }
1149
2364
  }
1150
- /** Open one exec channel. The caller owns the channel lifecycle. */
2365
+ /**
2366
+ * Open one exec channel. The caller owns the channel lifecycle.
2367
+ *
2368
+ * This channel spends an EXEC SLOT (same budget as `runExec`): it is a real
2369
+ * `conn.exec` session on the shared connection, so `MaxSessions` counts it
2370
+ * whether the pool does or not. The subprocess runtime opens these for every
2371
+ * command it runs (`p2/ssh-proc.ts`) and can have several in flight, which used
2372
+ * to be the one way to push the shared connection past its ceiling: sshd then
2373
+ * refuses the extra channel HARD — no retry, and the operation fails looking
2374
+ * like a broken host. A slot makes the surplus WAIT instead: bounded queue, then
2375
+ * a readable "busy" message naming the cause.
2376
+ */
1151
2377
  async execChannel(alias, command) {
1152
- const conn = await this.acquire(alias);
2378
+ const slots = this.slots;
2379
+ await this.acquireSlot(alias, slots);
2380
+ let conn;
2381
+ try {
2382
+ conn = await this.acquire(alias);
2383
+ } catch (error) {
2384
+ this.releaseSlot(alias, slots);
2385
+ throw error;
2386
+ }
1153
2387
  this.hold(alias);
2388
+ let released = false;
2389
+ /** Give the slot and the hold back exactly once (close and error may both fire). */
2390
+ const releaseOnce = () => {
2391
+ if (released) return;
2392
+ released = true;
2393
+ this.release(alias);
2394
+ this.releaseSlot(alias, slots);
2395
+ };
1154
2396
  try {
1155
2397
  const channel = await new Promise((resolve, reject) => {
1156
2398
  conn.exec(command, (error, stream) => {
@@ -1158,11 +2400,13 @@ var RemotePool = class {
1158
2400
  else resolve(stream);
1159
2401
  });
1160
2402
  });
1161
- channel.once("close", () => this.release(alias));
2403
+ channel.once("close", releaseOnce);
2404
+ channel.once("error", releaseOnce);
2405
+ this.countChannel(this.conns, alias, channel);
1162
2406
  this.markOk(alias);
1163
2407
  return channel;
1164
2408
  } catch (error) {
1165
- this.release(alias);
2409
+ releaseOnce();
1166
2410
  if (isConnectionFailure(error)) this.markError(alias, error);
1167
2411
  throw error;
1168
2412
  }
@@ -1184,9 +2428,39 @@ var RemotePool = class {
1184
2428
  * debug their network. Real transport failures still arrive through the
1185
2429
  * pooled connection's own close/error events.
1186
2430
  */
1187
- async forwardOut(alias, dstHost, dstPort, srcPort = 0) {
1188
- const conn = await this.acquire(alias);
1189
- this.hold(alias);
2431
+ async forwardOut(alias, dstHost, dstPort, srcPort = 0, opts = {}) {
2432
+ /**
2433
+ * Prefer the DEDICATED forward connection (see `forwardConns`). A host that
2434
+ * refuses the extra connection still forwards: the fallback is the shared
2435
+ * connection, i.e. exactly the old behaviour. The downgrade is logged once per
2436
+ * alias — a browser opens several forward channels per page, and one warning
2437
+ * per server refusal is information while one per channel is noise.
2438
+ *
2439
+ * Two short-circuits keep that preference from costing time:
2440
+ * - a recent refusal/timeout parks the alias for {@link FORWARD_DEDICATED_BLOCK_MS},
2441
+ * so the next channel goes straight to the shared connection;
2442
+ * - while a dedicated dial is already in flight, a second channel rides the
2443
+ * shared connection instead of waiting for the same handshake (it can only
2444
+ * be used by ONE `acquireIn` caller anyway).
2445
+ */
2446
+ let conn;
2447
+ let dedicated = opts.dedicated !== false;
2448
+ if (dedicated && this.forwardCoolingDown(alias)) dedicated = false;
2449
+ if (dedicated && this.forwardConns.get(alias)?.connecting !== void 0) dedicated = false;
2450
+ if (dedicated) try {
2451
+ conn = await this.acquireForward(alias);
2452
+ this.holdIn(this.forwardConns, alias);
2453
+ this.forwardBlocked.delete(alias);
2454
+ } catch (error) {
2455
+ dedicated = false;
2456
+ this.blockForward(alias, error);
2457
+ conn = await this.acquire(alias);
2458
+ this.hold(alias);
2459
+ }
2460
+ else {
2461
+ conn = await this.acquire(alias);
2462
+ this.hold(alias);
2463
+ }
1190
2464
  /**
1191
2465
  * What the channel-open callback does after the deadline already answered.
1192
2466
  *
@@ -1212,28 +2486,71 @@ var RemotePool = class {
1212
2486
  else resolve(stream);
1213
2487
  });
1214
2488
  }), CONTROL_TIMEOUT_MS, `forwarding channel to ${dstHost}:${dstPort} did not open within ${CONTROL_TIMEOUT_MS / 1e3}s`);
1215
- channel.once("close", () => this.release(alias));
1216
- this.markOk(alias);
1217
- return channel;
2489
+ channel.once("close", () => {
2490
+ if (dedicated) this.releaseIn(this.forwardConns, alias);
2491
+ else this.release(alias);
2492
+ });
2493
+ this.countChannel(dedicated ? this.forwardConns : this.conns, alias, channel);
2494
+ if (!dedicated) this.markOk(alias);
2495
+ return {
2496
+ channel,
2497
+ dedicated
2498
+ };
1218
2499
  } catch (error) {
1219
2500
  settled = true;
1220
- this.release(alias);
2501
+ if (dedicated) this.releaseIn(this.forwardConns, alias);
2502
+ else this.release(alias);
2503
+ /**
2504
+ * NO `markError` here — deliberately.
2505
+ *
2506
+ * ssh2 reports EVERY direct-tcpip failure as
2507
+ * `(SSH) Channel open failure: <reason>`, and the pool's
2508
+ * `CONNECTION_ERROR_RE` matches `channel open fail`. A closed remote port or
2509
+ * `AllowTcpForwarding no` therefore LOOKS like a transport failure and used
2510
+ * to paint the connection chip red (sending the user to debug a healthy
2511
+ * network, and putting the editor into read-only). The function's contract
2512
+ * is the opposite: a channel-open refusal is the RULE's failure
2513
+ * (`forward.lastError`), while real transport failures surface through the
2514
+ * pooled connection's own close/error events.
2515
+ */
1221
2516
  throw error;
1222
2517
  }
1223
2518
  }
2519
+ /**
2520
+ * Is this alias's dedicated forward connection in its short cooldown?
2521
+ *
2522
+ * Expired entries are dropped eagerly so the map cannot grow per alias forever.
2523
+ */
2524
+ forwardCoolingDown(alias) {
2525
+ const until = this.forwardBlocked.get(alias);
2526
+ if (until === void 0) return false;
2527
+ if (Date.now() >= until) {
2528
+ this.forwardBlocked.delete(alias);
2529
+ return false;
2530
+ }
2531
+ return true;
2532
+ }
2533
+ /** Park the dedicated connection for one alias and log the downgrade, once. */
2534
+ blockForward(alias, error) {
2535
+ this.forwardBlocked.set(alias, Date.now() + FORWARD_DEDICATED_BLOCK_MS);
2536
+ this.noteForwardFallback(alias, error);
2537
+ }
2538
+ /** Log one alias's forward downgrade to the shared connection, once. */
2539
+ noteForwardFallback(alias, error) {
2540
+ if (this.forwardFallbackNoted.has(alias)) return;
2541
+ this.forwardFallbackNoted.add(alias);
2542
+ const detail = error instanceof Error ? error.message : String(error ?? "");
2543
+ console.warn(`[dsh-remote-vs] dedicated forward connection to ${alias} failed; using the shared one:`, detail);
2544
+ }
1224
2545
  /** Run one callback with a fresh SFTP session (closed afterwards). */
1225
2546
  async withSftp(alias, fn, opts = {}) {
1226
- await this.acquireSlot(alias);
1227
- let conn;
2547
+ const lane = await this.acquireSftp(alias);
2548
+ const slots = this.laneSlots(lane.lane);
2549
+ const connMap = this.laneConns(lane.lane);
2550
+ await this.acquireSlot(alias, slots);
2551
+ this.holdIn(connMap, alias);
1228
2552
  try {
1229
- conn = await this.acquire(alias);
1230
- } catch (error) {
1231
- this.releaseSlot(alias);
1232
- throw error;
1233
- }
1234
- this.hold(alias);
1235
- try {
1236
- const sftp = await this.openSession(conn);
2553
+ const sftp = await this.openSession(lane.conn, alias, connMap);
1237
2554
  try {
1238
2555
  const limit = opts.timeoutMs ?? SFTP_OP_TIMEOUT_MS;
1239
2556
  const result = limit <= 0 ? await fn(sftp) : await withDeadline(fn(sftp), limit, `SFTP operation timed out after ${limit / 1e3}s`);
@@ -1248,8 +2565,8 @@ var RemotePool = class {
1248
2565
  this.noteOpFailure(alias, error);
1249
2566
  throw error;
1250
2567
  } finally {
1251
- this.release(alias);
1252
- this.releaseSlot(alias);
2568
+ this.releaseIn(connMap, alias);
2569
+ this.releaseSlot(alias, slots);
1253
2570
  }
1254
2571
  }
1255
2572
  /**
@@ -1282,24 +2599,28 @@ var RemotePool = class {
1282
2599
  const sessions = [];
1283
2600
  let slots = 0;
1284
2601
  let holds = 0;
2602
+ /** Which lane the transfer got; undefined until the acquisition succeeded. */
2603
+ let lane;
1285
2604
  /** Set when the callback settles: a late `addChannel` must not leak resources. */
1286
2605
  let closed = false;
1287
- let conn;
1288
2606
  try {
1289
- await this.acquireSlot(alias);
2607
+ const lease = await this.acquireSftp(alias);
2608
+ lane = lease.lane;
2609
+ const slotTable = this.laneSlots(lease.lane);
2610
+ const connMap = this.laneConns(lease.lane);
2611
+ await this.acquireSlot(alias, slotTable);
1290
2612
  slots += 1;
1291
- conn = await this.acquire(alias);
1292
- this.hold(alias);
2613
+ this.holdIn(connMap, alias);
1293
2614
  holds += 1;
1294
- sessions.push(await this.openSession(conn));
2615
+ sessions.push(await this.openSession(lease.conn, alias, connMap));
1295
2616
  const addChannel = async () => {
1296
2617
  if (closed) return void 0;
1297
- if (!this.tryAcquireSlot(alias)) return void 0;
2618
+ if (!this.tryAcquireSlot(alias, slotTable)) return void 0;
1298
2619
  slots += 1;
1299
- this.hold(alias);
2620
+ this.holdIn(connMap, alias);
1300
2621
  holds += 1;
1301
2622
  try {
1302
- const extra = await this.openSession(conn);
2623
+ const extra = await this.openSession(lease.conn, alias, connMap);
1303
2624
  if (closed) {
1304
2625
  try {
1305
2626
  extra.end();
@@ -1323,8 +2644,10 @@ var RemotePool = class {
1323
2644
  for (const session of sessions) try {
1324
2645
  session.end();
1325
2646
  } catch {}
1326
- for (let i = 0; i < holds; i += 1) this.release(alias);
1327
- for (let i = 0; i < slots; i += 1) this.releaseSlot(alias);
2647
+ if (lane !== void 0) {
2648
+ for (let i = 0; i < holds; i += 1) this.releaseIn(this.laneConns(lane), alias);
2649
+ for (let i = 0; i < slots; i += 1) this.releaseSlot(alias, this.laneSlots(lane));
2650
+ }
1328
2651
  }
1329
2652
  }
1330
2653
  /**
@@ -1418,8 +2741,11 @@ var RemotePool = class {
1418
2741
  * place that can still see the session, and a late one would otherwise leak a
1419
2742
  * server-side channel that no slot or hold accounts for (the caller has long
1420
2743
  * returned its own and moved on).
2744
+ *
2745
+ * `alias`/`map` name the connection the session rides, so the channel it holds
2746
+ * is counted on the right lane (see `countChannel`).
1421
2747
  */
1422
- openSession(conn) {
2748
+ openSession(conn, alias, map) {
1423
2749
  return new Promise((resolve, reject) => {
1424
2750
  let settled = false;
1425
2751
  const timer = setTimeout(() => {
@@ -1437,8 +2763,12 @@ var RemotePool = class {
1437
2763
  }
1438
2764
  settled = true;
1439
2765
  clearTimeout(timer);
1440
- if (error !== void 0 && error !== null) reject(error);
1441
- else resolve(session);
2766
+ if (error !== void 0 && error !== null) {
2767
+ reject(error);
2768
+ return;
2769
+ }
2770
+ this.countChannel(map, alias, session);
2771
+ resolve(session);
1442
2772
  };
1443
2773
  try {
1444
2774
  conn.sftp((error, session) => finish(error, session));
@@ -1487,20 +2817,21 @@ var RemotePool = class {
1487
2817
  /**
1488
2818
  * Open the browse session: a channel slot + a connection hold + the SFTP
1489
2819
  * session itself, all released together by evictBrowse().
2820
+ *
2821
+ * The lane is chosen HERE, once per session, and recorded on the state: the
2822
+ * eviction path must give the slot and the hold back to the connection that
2823
+ * actually served the session (dedicated SFTP, or the shared fallback).
1490
2824
  */
1491
2825
  async openBrowse(alias, state) {
1492
- await this.acquireSlot(alias);
1493
- let conn;
1494
- try {
1495
- conn = await this.acquire(alias);
1496
- } catch (error) {
1497
- this.releaseSlot(alias);
1498
- throw error;
1499
- }
1500
- this.hold(alias);
2826
+ const lane = await this.acquireSftp(alias);
2827
+ state.lane = lane.lane;
2828
+ const slots = this.laneSlots(lane.lane);
2829
+ const connMap = this.laneConns(lane.lane);
2830
+ await this.acquireSlot(alias, slots);
2831
+ this.holdIn(connMap, alias);
1501
2832
  state.leased = true;
1502
2833
  try {
1503
- const sftp = await this.openSession(conn);
2834
+ const sftp = await this.openSession(lane.conn, alias, connMap);
1504
2835
  if (this.browsed.get(alias) !== state || !state.leased) {
1505
2836
  try {
1506
2837
  sftp.end();
@@ -1559,8 +2890,8 @@ var RemotePool = class {
1559
2890
  } catch {}
1560
2891
  if (state.leased) {
1561
2892
  state.leased = false;
1562
- this.release(alias);
1563
- this.releaseSlot(alias);
2893
+ this.releaseIn(this.laneConns(state.lane), alias);
2894
+ this.releaseSlot(alias, this.laneSlots(state.lane));
1564
2895
  }
1565
2896
  }
1566
2897
  browseState(alias) {
@@ -1572,19 +2903,24 @@ var RemotePool = class {
1572
2903
  active: 0,
1573
2904
  stale: false,
1574
2905
  leased: false,
2906
+ lane: "shared",
1575
2907
  idle: void 0
1576
2908
  };
1577
2909
  this.browsed.set(alias, created);
1578
2910
  return created;
1579
2911
  }
1580
2912
  /**
1581
- * Take one channel slot for `alias`, waiting FIFO when the limit is reached.
1582
- * The wait is bounded: waiting forever behind a peer that never finishes is
1583
- * worse than a readable error naming the cause and what to do about it.
2913
+ * Take one channel slot for `alias` on the budget `slots` names, waiting FIFO
2914
+ * when the limit is reached. The wait is bounded: waiting forever behind a peer
2915
+ * that never finishes is worse than a readable error naming the cause.
2916
+ *
2917
+ * `slots` defaults to the SHARED connection's exec budget — the table every
2918
+ * caller meant before the lanes existed; dedicated-lane callers pass theirs.
1584
2919
  */
1585
- async acquireSlot(alias) {
1586
- const state = this.slotState(alias);
1587
- if (state.active < CHANNEL_LIMIT) {
2920
+ async acquireSlot(alias, slots = this.slots) {
2921
+ const { limit, noun } = this.budgetOf(slots);
2922
+ const state = this.slotState(alias, slots);
2923
+ if (state.active < limit) {
1588
2924
  state.active += 1;
1589
2925
  return;
1590
2926
  }
@@ -1600,13 +2936,41 @@ var RemotePool = class {
1600
2936
  waiter.granted = true;
1601
2937
  const index = state.queue.indexOf(waiter);
1602
2938
  if (index >= 0) state.queue.splice(index, 1);
1603
- reject(/* @__PURE__ */ new Error(`remote host ${alias} is busy: ${CHANNEL_LIMIT} operations already hold channels (this one waited ${CHANNEL_WAIT_MS / 1e3}s — retry once the earlier work finishes)`));
2939
+ reject(/* @__PURE__ */ new Error(`remote host ${alias} is busy: ${limit} ${noun} already hold channels (this one waited ${CHANNEL_WAIT_MS / 1e3}s — retry once the earlier work finishes)`));
1604
2940
  }, CHANNEL_WAIT_MS);
1605
2941
  waiter.timer.unref?.();
1606
2942
  state.queue.push(waiter);
1607
2943
  });
1608
2944
  }
1609
2945
  /**
2946
+ * The ceiling and the wording of one budget.
2947
+ *
2948
+ * The TABLE is the budget's identity: a caller that hands in a table gets that
2949
+ * budget's own ceiling AND its own nouns, so a full network lane says "2
2950
+ * network operations already hold channels" and a full git lane says "2 git
2951
+ * commands already hold channels" instead of borrowing the exec sentence — a
2952
+ * user reading "5 operations" about a two-slot lane would go looking for
2953
+ * operations that do not exist. A new budget is described here, once.
2954
+ */
2955
+ budgetOf(slots) {
2956
+ if (slots === this.netSlots) return {
2957
+ limit: NET_CHANNEL_LIMIT,
2958
+ noun: "network operations"
2959
+ };
2960
+ if (slots === this.gitSlots) return {
2961
+ limit: GIT_CHANNEL_LIMIT,
2962
+ noun: "git commands"
2963
+ };
2964
+ if (slots === this.sftpSlots) return {
2965
+ limit: SFTP_CHANNEL_LIMIT,
2966
+ noun: "operations"
2967
+ };
2968
+ return {
2969
+ limit: CHANNEL_LIMIT,
2970
+ noun: "operations"
2971
+ };
2972
+ }
2973
+ /**
1610
2974
  * Take one channel slot only if one is free RIGHT NOW; never queue.
1611
2975
  *
1612
2976
  * Optional work (a bulk transfer's second channel) must not wait behind
@@ -1616,15 +2980,16 @@ var RemotePool = class {
1616
2980
  * the attempt on purpose — it has been waiting longer, and stealing its slot
1617
2981
  * would just move the wait.
1618
2982
  */
1619
- tryAcquireSlot(alias) {
1620
- const state = this.slotState(alias);
1621
- if (state.active >= CHANNEL_LIMIT || state.queue.length > 0) return false;
2983
+ tryAcquireSlot(alias, slots = this.slots) {
2984
+ const { limit } = this.budgetOf(slots);
2985
+ const state = this.slotState(alias, slots);
2986
+ if (state.active >= limit || state.queue.length > 0) return false;
1622
2987
  state.active += 1;
1623
2988
  return true;
1624
2989
  }
1625
- /** Give a slot back, handing it straight to the longest-waiting operation. */
1626
- releaseSlot(alias) {
1627
- const state = this.slots.get(alias);
2990
+ /** Give a slot back to its budget, handing it straight to the longest waiter. */
2991
+ releaseSlot(alias, slots = this.slots) {
2992
+ const state = slots.get(alias);
1628
2993
  if (state === void 0) return;
1629
2994
  const waiter = state.queue.shift();
1630
2995
  if (waiter !== void 0) {
@@ -1634,16 +2999,16 @@ var RemotePool = class {
1634
2999
  return;
1635
3000
  }
1636
3001
  if (state.active > 0) state.active -= 1;
1637
- if (state.active === 0) this.slots.delete(alias);
3002
+ if (state.active === 0) slots.delete(alias);
1638
3003
  }
1639
- slotState(alias) {
1640
- const existing = this.slots.get(alias);
3004
+ slotState(alias, slots) {
3005
+ const existing = slots.get(alias);
1641
3006
  if (existing !== void 0) return existing;
1642
3007
  const created = {
1643
3008
  active: 0,
1644
3009
  queue: []
1645
3010
  };
1646
- this.slots.set(alias, created);
3011
+ slots.set(alias, created);
1647
3012
  return created;
1648
3013
  }
1649
3014
  /**
@@ -1694,27 +3059,156 @@ var RemotePool = class {
1694
3059
  pooled.timer = void 0;
1695
3060
  }
1696
3061
  }
1697
- release(alias) {
1698
- this.releaseIn(this.conns, alias);
3062
+ release(alias) {
3063
+ this.releaseIn(this.conns, alias);
3064
+ }
3065
+ /**
3066
+ * Count one SSH channel that is now open on a pooled connection, and give the
3067
+ * number back when the channel closes.
3068
+ *
3069
+ * `held` is NOT this number (see `Pooled.channels`): a jump tunnel pins the
3070
+ * jump host twice for its single channel, and `stats()` reports both, so the
3071
+ * monitor page never prints a hold count as a channel count. The close listener
3072
+ * mutates the entry OBJECT it was registered on, so a channel that outlives its
3073
+ * entry cannot decrement the counter of a successor entry.
3074
+ *
3075
+ * The entry is looked up when the channel is COUNTED, so a session that answers
3076
+ * pathologically late (after `drop()` and a fresh dial) is charged to the
3077
+ * successor entry and given back when it closes. Accepted: the window needs a
3078
+ * reply that outlives a host edit, the number is diagnostic, and the pair is
3079
+ * still symmetric (one increment, one decrement).
3080
+ */
3081
+ countChannel(map, alias, channel) {
3082
+ const pooled = map.get(alias);
3083
+ if (pooled === void 0 || typeof channel.on !== "function") return;
3084
+ pooled.channels = (pooled.channels ?? 0) + 1;
3085
+ let counted = true;
3086
+ channel.on("close", () => {
3087
+ if (!counted) return;
3088
+ counted = false;
3089
+ if (pooled.channels > 0) pooled.channels -= 1;
3090
+ });
3091
+ }
3092
+ releaseIn(map, alias) {
3093
+ const pooled = map.get(alias);
3094
+ if (pooled === void 0) return;
3095
+ if (pooled.held > 0) pooled.held -= 1;
3096
+ pooled.lastUse = Date.now();
3097
+ if (pooled.held > 0) return;
3098
+ if (pooled.timer !== void 0) clearTimeout(pooled.timer);
3099
+ pooled.timer = setTimeout(() => this.evictFrom(map, alias), IDLE_MS);
3100
+ if (typeof pooled.timer === "object" && "unref" in pooled.timer) pooled.timer.unref();
3101
+ }
3102
+ async acquire(alias) {
3103
+ return this.acquireIn(this.conns, alias);
3104
+ }
3105
+ /** `acquire` for the dedicated PTY connection map. */
3106
+ async acquireShell(alias) {
3107
+ return this.acquireIn(this.shellConns, alias);
3108
+ }
3109
+ /**
3110
+ * `acquire` for the dedicated port-forward connection map.
3111
+ *
3112
+ * `quiet`: a dedicated forward connection is an OPTIMIZATION. If the server
3113
+ * refuses it (MaxStartups, `MaxSessions`, a per-source limit) the forward still
3114
+ * works over the shared connection, so the shared link is healthy — painting
3115
+ * the connection chip red here would send the user to debug a network that is
3116
+ * fine (and `forwardOut` reports the rule's own error separately).
3117
+ *
3118
+ * The dial also gets its OWN short budget ({@link FORWARD_DEDICATED_BUDGET_MS}):
3119
+ * a server that silently drops the extra connection would otherwise make every
3120
+ * forward channel wait the full connect watchdog before falling back. The
3121
+ * abandoned dial keeps running — if it eventually succeeds the connection is
3122
+ * pooled and the next channel uses it; its failure is already handled inside
3123
+ * `acquireIn`.
3124
+ */
3125
+ async acquireForward(alias) {
3126
+ const dialing = this.acquireIn(this.forwardConns, alias, true);
3127
+ try {
3128
+ return await withDeadline(dialing, FORWARD_DEDICATED_BUDGET_MS, `dedicated forward connection to ${alias} did not settle within ${FORWARD_DEDICATED_BUDGET_MS / 1e3}s`);
3129
+ } catch (error) {
3130
+ dialing.catch(() => void 0);
3131
+ throw error;
3132
+ }
3133
+ }
3134
+ /**
3135
+ * Take the connection a FILE operation should ride: the dedicated SFTP one,
3136
+ * else the shared one (recorded as the fallback).
3137
+ *
3138
+ * Same three-part shape as the PTY/forward precedents, for the same reasons:
3139
+ *
3140
+ * 1. `quiet` on the dial — a dedicated connection is an optional isolation, so
3141
+ * the server refusing it (MaxStartups, a per-user limit) says nothing about
3142
+ * the shared link and must not paint the connection chip red.
3143
+ * 2. A short own budget ({@link SFTP_DEDICATED_BUDGET_MS}) — browsing is one
3144
+ * request per folder, so waiting out the 45 s connect watchdog before falling
3145
+ * back would freeze the explorer. The abandoned dial keeps running: if it
3146
+ * eventually succeeds the connection is pooled and the next request uses it.
3147
+ * 3. A cooldown ({@link SFTP_DEDICATED_BLOCK_MS}) — without it every browse
3148
+ * request would pay that budget again. A success or `drop()` clears it.
3149
+ *
3150
+ * The shared fallback's own dial failure is NOT quiet (it is a real link
3151
+ * failure and `acquire` reports it as one).
3152
+ */
3153
+ async acquireSftp(alias) {
3154
+ if (!this.sftpCoolingDown(alias)) {
3155
+ const dialing = this.acquireIn(this.sftpConns, alias, true);
3156
+ try {
3157
+ const conn = await withDeadline(dialing, SFTP_DEDICATED_BUDGET_MS, `dedicated file connection to ${alias} did not settle within ${SFTP_DEDICATED_BUDGET_MS / 1e3}s`);
3158
+ this.sftpBlocked.delete(alias);
3159
+ this.sftpFallback.delete(alias);
3160
+ return {
3161
+ conn,
3162
+ lane: "sftp"
3163
+ };
3164
+ } catch (error) {
3165
+ dialing.catch(() => void 0);
3166
+ this.blockSftp(alias, error);
3167
+ }
3168
+ }
3169
+ const conn = await this.acquire(alias);
3170
+ this.sftpFallback.add(alias);
3171
+ return {
3172
+ conn,
3173
+ lane: "shared"
3174
+ };
3175
+ }
3176
+ /** The pooled map behind a lane: the dedicated SFTP connection, or the shared one. */
3177
+ laneConns(lane) {
3178
+ return lane === "sftp" ? this.sftpConns : this.conns;
1699
3179
  }
1700
- releaseIn(map, alias) {
1701
- const pooled = map.get(alias);
1702
- if (pooled === void 0) return;
1703
- if (pooled.held > 0) pooled.held -= 1;
1704
- pooled.lastUse = Date.now();
1705
- if (pooled.held > 0) return;
1706
- if (pooled.timer !== void 0) clearTimeout(pooled.timer);
1707
- pooled.timer = setTimeout(() => this.evictFrom(map, alias), IDLE_MS);
1708
- if (typeof pooled.timer === "object" && "unref" in pooled.timer) pooled.timer.unref();
3180
+ /** The channel budget behind a lane: each connection has its own `MaxSessions`. */
3181
+ laneSlots(lane) {
3182
+ return lane === "sftp" ? this.sftpSlots : this.slots;
1709
3183
  }
1710
- async acquire(alias) {
1711
- return this.acquireIn(this.conns, alias);
3184
+ /**
3185
+ * Is this alias's dedicated SFTP connection in its short cooldown?
3186
+ *
3187
+ * Expired entries are dropped eagerly so the map cannot grow per alias forever.
3188
+ */
3189
+ sftpCoolingDown(alias) {
3190
+ const until = this.sftpBlocked.get(alias);
3191
+ if (until === void 0) return false;
3192
+ if (Date.now() >= until) {
3193
+ this.sftpBlocked.delete(alias);
3194
+ return false;
3195
+ }
3196
+ return true;
1712
3197
  }
1713
- /** `acquire` for the dedicated PTY connection map. */
1714
- async acquireShell(alias) {
1715
- return this.acquireIn(this.shellConns, alias);
3198
+ /** Park the dedicated SFTP connection for one alias and log the downgrade, once. */
3199
+ blockSftp(alias, error) {
3200
+ this.sftpBlocked.set(alias, Date.now() + SFTP_DEDICATED_BLOCK_MS);
3201
+ this.sftpFallback.add(alias);
3202
+ this.noteSftpFallback(alias, error);
3203
+ }
3204
+ /** Log one alias's file-operation downgrade to the shared connection, once. */
3205
+ noteSftpFallback(alias, error) {
3206
+ if (this.sftpFallbackNoted.has(alias)) return;
3207
+ this.sftpFallbackNoted.add(alias);
3208
+ const detail = error instanceof Error ? error.message : String(error ?? "");
3209
+ console.warn(`[dsh-remote-vs] dedicated file connection to ${alias} failed; using the shared one:`, detail);
1716
3210
  }
1717
- async acquireIn(map, alias) {
3211
+ async acquireIn(map, alias, quiet = false) {
1718
3212
  const pooled = map.get(alias);
1719
3213
  if (pooled !== void 0 && pooled.connecting !== void 0) return pooled.connecting;
1720
3214
  if (pooled !== void 0) {
@@ -1726,7 +3220,8 @@ var RemotePool = class {
1726
3220
  timer: void 0,
1727
3221
  lastUse: Date.now(),
1728
3222
  connecting: void 0,
1729
- held: 0
3223
+ held: 0,
3224
+ channels: 0
1730
3225
  };
1731
3226
  map.set(alias, entry);
1732
3227
  /**
@@ -1740,7 +3235,9 @@ var RemotePool = class {
1740
3235
  * so no idle timer arms, and `dispose()` only walks the map. Without the
1741
3236
  * failure check, a failed OLD dial deletes the NEW entry by alias.
1742
3237
  */
1743
- entry.connecting = this.dial(alias).then((conn) => {
3238
+ entry.connecting = this.dial(alias, (egress) => {
3239
+ if (map.get(alias) === entry) entry.egress = egress;
3240
+ }).then((conn) => {
1744
3241
  if (map.get(alias) !== entry) {
1745
3242
  try {
1746
3243
  conn.end();
@@ -1749,22 +3246,22 @@ var RemotePool = class {
1749
3246
  }
1750
3247
  entry.conn = conn;
1751
3248
  entry.connecting = void 0;
1752
- this.markOk(alias);
3249
+ if (!quiet) this.markOk(alias);
1753
3250
  conn.on("close", () => {
1754
3251
  if (map.get(alias) !== entry) return;
1755
- this.markError(alias, /* @__PURE__ */ new Error("connection closed"));
3252
+ if (!quiet) this.markError(alias, /* @__PURE__ */ new Error("connection closed"));
1756
3253
  this.evictFrom(map, alias);
1757
3254
  });
1758
3255
  conn.on("error", (error) => {
1759
3256
  if (map.get(alias) !== entry) return;
1760
- this.markError(alias, error);
3257
+ if (!quiet) this.markError(alias, error);
1761
3258
  this.evictFrom(map, alias);
1762
3259
  });
1763
3260
  this.releaseIn(map, alias);
1764
3261
  return conn;
1765
3262
  }, (error) => {
1766
3263
  if (map.get(alias) === entry) map.delete(alias);
1767
- this.markError(alias, error);
3264
+ if (!quiet) this.markError(alias, error);
1768
3265
  throw error;
1769
3266
  });
1770
3267
  return entry.connecting;
@@ -1775,6 +3272,7 @@ var RemotePool = class {
1775
3272
  if (pooled === void 0) return;
1776
3273
  map.delete(alias);
1777
3274
  if (pooled.timer !== void 0) clearTimeout(pooled.timer);
3275
+ pooled.egress = void 0;
1778
3276
  try {
1779
3277
  pooled.conn.end();
1780
3278
  } catch {}
@@ -1790,8 +3288,126 @@ var RemotePool = class {
1790
3288
  makeClient() {
1791
3289
  return new import_lib.Client();
1792
3290
  }
1793
- dial(alias) {
3291
+ /**
3292
+ * Open the transport `alias`'s configured route requires, WITHOUT dialing SSH.
3293
+ *
3294
+ * This is the part of {@link dial} that turns a `ResolvedProxy` decision into a
3295
+ * socket: nothing for a direct route, a tunnel socket for a proxy, and a
3296
+ * `direct-tcpip` channel riding the jump host's pooled connection for a jump.
3297
+ * Extracted so a SECOND ssh2 dialer — p2's helper transport, which owns its own
3298
+ * `Client` — takes exactly the same route instead of a bare direct connection
3299
+ * (otherwise a host reachable only through a proxy or jump host answers exec and
3300
+ * SFTP but fails every file/Git fast path).
3301
+ *
3302
+ * `route` may be passed in when the caller has already resolved it and needs the
3303
+ * decision for its own purposes (`dial` reports the egress it settled on): the
3304
+ * default resolves it from the store.
3305
+ *
3306
+ * The returned `release` is IDEMPOTENT and belongs to the caller: it tears down
3307
+ * the tunnel (destroys the proxy socket / closes the channel and gives the jump
3308
+ * host's hold back). It must be called exactly once by whoever owns the socket —
3309
+ * on failure, on close, and on dispose. A direct route has nothing to release,
3310
+ * so it gets a no-op.
3311
+ */
3312
+ async openRoute(alias, route = this.store.resolveProxy(alias)) {
3313
+ const host = this.store.require(alias);
3314
+ /** The socket ssh2 will ride, when a proxy/jump built one. */
3315
+ let sock;
3316
+ /** Runs once: tears the tunnel down (close the channel, release the jump). */
3317
+ let releaseTunnel;
3318
+ if (route.kind === "proxy") {
3319
+ try {
3320
+ sock = await openProxySocket(route.proxy, host.host, host.port);
3321
+ } catch (error) {
3322
+ throw proxyDialError(error, route.proxy);
3323
+ }
3324
+ releaseTunnel = () => {
3325
+ try {
3326
+ sock?.destroy();
3327
+ } catch {}
3328
+ };
3329
+ } else if (route.kind === "jump") {
3330
+ const via = route.viaAlias;
3331
+ try {
3332
+ await this.acquire(via);
3333
+ this.hold(via);
3334
+ } catch (error) {
3335
+ throw new Error(`jump host "${via}" failed: ${messageOf$3(error)}`);
3336
+ }
3337
+ let channel;
3338
+ try {
3339
+ channel = (await this.forwardOut(via, host.host, host.port, 0, { dedicated: false })).channel;
3340
+ } catch (error) {
3341
+ this.release(via);
3342
+ throw new Error(`jump host "${via}" failed: ${messageOf$3(error)}`);
3343
+ }
3344
+ let released = false;
3345
+ releaseTunnel = () => {
3346
+ if (released) return;
3347
+ released = true;
3348
+ try {
3349
+ channel.close();
3350
+ } catch {}
3351
+ this.release(via);
3352
+ };
3353
+ sock = channel;
3354
+ }
3355
+ return {
3356
+ ...sock === void 0 ? {} : { sock },
3357
+ release: releaseTunnel ?? (() => {})
3358
+ };
3359
+ }
3360
+ /**
3361
+ * The routed transport for `alias`, for a caller that dials its OWN ssh2 client.
3362
+ *
3363
+ * Same decision, same error layering (`proxy auth failed: …`, `jump host "x"
3364
+ * failed: …`), same socket as a pooled connection would ride — p2's helper
3365
+ * transport uses this so "reachable only through the jump host" stops meaning
3366
+ * "exec works, files do not".
3367
+ *
3368
+ * **The caller owns the result**: when `sock` is set, ssh2 must be given `{ sock }`
3369
+ * and NOT `host`/`port` (both together let ssh2 choose between dialing the target
3370
+ * itself and riding the tunnel). `release` must be called exactly once — on
3371
+ * failure, on the connection's close, and on dispose — or the jump host's hold
3372
+ * leaks and the proxy socket stays open.
3373
+ */
3374
+ async openRoutedSocket(alias) {
3375
+ return this.openRoute(alias);
3376
+ }
3377
+ /**
3378
+ * Open one SSH connection, through whatever route the store resolves.
3379
+ *
3380
+ * Three routes, and only the first is the pre-proxy code path:
3381
+ * - `direct`: unchanged (`host` / `port` in the connect config);
3382
+ * - `proxy`: the proxy module builds the tunnel and ssh2 rides the returned
3383
+ * socket (`sock`), so `host`/`port` are deliberately omitted (ssh2 ignores
3384
+ * them when `sock` is present);
3385
+ * - `jump`: the tunnel is a `direct-tcpip` channel on the JUMP host's pooled
3386
+ * connection, held for as long as the client lives. Its close/error handlers
3387
+ * close that channel and give the hold back — a leak here would pin the jump
3388
+ * host's connection forever.
3389
+ *
3390
+ * Every failure is a DIAL failure, so it keeps the existing `markError`
3391
+ * semantics; only the message is layered, so the user can tell which hop broke:
3392
+ * `proxy auth failed: …`, `proxy refused: …`, `jump host "x" failed: …`.
3393
+ *
3394
+ * `report` receives the route this dial ACTUALLY settled on, once and only on
3395
+ * success — a caller that asked "did this go through the jump host?" must not
3396
+ * be answered from a configuration that may have changed since. It is a
3397
+ * callback rather than a wider return type so the seam keeps returning the
3398
+ * `Client` the existing callers (and gates) hand around.
3399
+ */
3400
+ async dial(alias, report) {
1794
3401
  const host = this.store.require(alias);
3402
+ const route = this.store.resolveProxy(alias);
3403
+ const egress = egressOf(route, host);
3404
+ /**
3405
+ * The transport this connection rides. Resolved with the SAME route the egress
3406
+ * was computed from, so the reported hop and the socket can never disagree —
3407
+ * and `openRoute` builds it exactly the way this method used to inline
3408
+ * (proxy tunnel socket / jump-host `direct-tcpip` channel / nothing at all).
3409
+ */
3410
+ const routed = await this.openRoute(alias, route);
1795
3411
  return new Promise((resolve, reject) => {
1796
3412
  const conn = this.makeClient();
1797
3413
  let settled = false;
@@ -1803,12 +3419,14 @@ var RemotePool = class {
1803
3419
  try {
1804
3420
  conn.end();
1805
3421
  } catch {}
3422
+ routed.release();
1806
3423
  reject(explainAuthError(host, error));
1807
3424
  };
1808
3425
  conn.on("ready", () => {
1809
3426
  if (settled) return;
1810
3427
  settled = true;
1811
3428
  if (guard !== void 0) clearTimeout(guard);
3429
+ report?.(egress);
1812
3430
  resolve(conn);
1813
3431
  });
1814
3432
  conn.on("error", (error) => fail(error));
@@ -1820,6 +3438,8 @@ var RemotePool = class {
1820
3438
  * leave this promise pending forever while the caller held a channel slot.
1821
3439
  */
1822
3440
  conn.on("close", () => fail(/* @__PURE__ */ new Error("connection closed during SSH handshake")));
3441
+ conn.once("close", () => routed.release());
3442
+ conn.once("error", () => routed.release());
1823
3443
  guard = setTimeout(() => {
1824
3444
  fail(/* @__PURE__ */ new Error(`SSH handshake did not settle within ${(READY_TIMEOUT_MS + DIAL_GUARD_MARGIN_MS) / 1e3}s`));
1825
3445
  }, READY_TIMEOUT_MS + DIAL_GUARD_MARGIN_MS);
@@ -1845,11 +3465,14 @@ var RemotePool = class {
1845
3465
  return true;
1846
3466
  };
1847
3467
  try {
3468
+ const transport = routed.sock === void 0 ? {
3469
+ host: host.host,
3470
+ port: host.port
3471
+ } : { sock: routed.sock };
1848
3472
  if (host.auth.kind === "key") {
1849
3473
  const keyPath = host.auth.keyPath;
1850
3474
  conn.connect({
1851
- host: host.host,
1852
- port: host.port,
3475
+ ...transport,
1853
3476
  username: host.user,
1854
3477
  privateKey: readFileSync(keyPath),
1855
3478
  passphrase: host.auth.passphrase,
@@ -1859,8 +3482,7 @@ var RemotePool = class {
1859
3482
  hostVerifier
1860
3483
  });
1861
3484
  } else conn.connect({
1862
- host: host.host,
1863
- port: host.port,
3485
+ ...transport,
1864
3486
  username: host.user,
1865
3487
  password: host.auth.password,
1866
3488
  tryKeyboard: true,
@@ -1876,6 +3498,83 @@ var RemotePool = class {
1876
3498
  }
1877
3499
  };
1878
3500
  /**
3501
+ * The route one resolved proxy decision describes, in the shape the chip prints.
3502
+ *
3503
+ * `detail` is the HOP, never a sentence: the target `host:port` for a direct
3504
+ * connection, the proxy `host:port` for a tunnel, the jump host's alias for a
3505
+ * chain. The wording belongs to the localized client — a second English sentence
3506
+ * baked in here would leak into the Chinese tooltip.
3507
+ */
3508
+ function egressOf(route, host) {
3509
+ if (route.kind === "proxy") return {
3510
+ kind: "proxy",
3511
+ detail: `${route.proxy.host}:${route.proxy.port}`,
3512
+ source: route.source,
3513
+ proxyKind: route.proxy.kind
3514
+ };
3515
+ if (route.kind === "jump") return {
3516
+ kind: "jump",
3517
+ detail: route.viaAlias,
3518
+ viaAlias: route.viaAlias
3519
+ };
3520
+ return {
3521
+ kind: "direct",
3522
+ detail: `${host.host}:${host.port}`
3523
+ };
3524
+ }
3525
+ /**
3526
+ * Best-effort route from the STORED fields, for the one case `resolveProxy`
3527
+ * refuses to answer (a dangling jump chain, a self-jump, a proxy setting that
3528
+ * does not validate). The caller adds `problem` with the reason; the shape here
3529
+ * only says WHICH kind of route is broken, so the chip can name it.
3530
+ */
3531
+ function storedEgress(host) {
3532
+ const jump = host.proxy?.jump?.viaAlias;
3533
+ if (host.proxy?.mode === "jump") return {
3534
+ kind: "jump",
3535
+ detail: jump ?? "",
3536
+ ...jump === void 0 ? {} : { viaAlias: jump }
3537
+ };
3538
+ const proxy = host.proxy?.proxy;
3539
+ if (proxy !== void 0) return {
3540
+ kind: "proxy",
3541
+ detail: `${proxy.host}:${proxy.port}`,
3542
+ proxyKind: proxy.kind
3543
+ };
3544
+ return {
3545
+ kind: "direct",
3546
+ detail: `${host.host}:${host.port}`
3547
+ };
3548
+ }
3549
+ /** Message of an unknown thrown value, without assuming it is an `Error`. */
3550
+ function messageOf$3(error) {
3551
+ return error instanceof Error ? error.message : String(error ?? "");
3552
+ }
3553
+ /**
3554
+ * Fixed prefix per proxy failure reason.
3555
+ *
3556
+ * The dial fails either way; the prefix is what tells the user WHICH layer broke —
3557
+ * their password, the proxy host, the tunnel policy, or the destination. The raw
3558
+ * detail is kept after it, so nothing is lost.
3559
+ */
3560
+ const PROXY_FAILURE_PREFIX = {
3561
+ unreachable: "proxy unreachable",
3562
+ timeout: "proxy timed out",
3563
+ auth: "proxy auth failed",
3564
+ refused: "proxy refused",
3565
+ protocol: "proxy protocol error",
3566
+ target: "proxy target invalid"
3567
+ };
3568
+ /** One proxy dial failure, with the layer in front of the original message. */
3569
+ function proxyDialError(error, proxy) {
3570
+ if (error instanceof ProxyError) {
3571
+ const prefix = PROXY_FAILURE_PREFIX[error.reason];
3572
+ const where = error.reason === "target" ? "" : ` ${proxy.kind} proxy ${proxy.host}:${proxy.port}`;
3573
+ return /* @__PURE__ */ new Error(`${prefix}${where}: ${error.message}`);
3574
+ }
3575
+ return /* @__PURE__ */ new Error(`proxy failed: ${proxy.kind} proxy ${proxy.host}:${proxy.port}: ${messageOf$3(error)}`);
3576
+ }
3577
+ /**
1879
3578
  * Translate ssh2's generic auth failure into something actionable. Never
1880
3579
  * includes secrets — only the entry shape and the likely server-side causes.
1881
3580
  */
@@ -2182,6 +3881,7 @@ var ForwardManager = class {
2182
3881
  bytesIn: 0,
2183
3882
  bytesOut: 0,
2184
3883
  lastError: void 0,
3884
+ transport: void 0,
2185
3885
  startedAt: Date.now()
2186
3886
  };
2187
3887
  server.on("connection", (socket) => {
@@ -2246,7 +3946,16 @@ var ForwardManager = class {
2246
3946
  async connect(forward, socket) {
2247
3947
  let channel;
2248
3948
  try {
2249
- channel = await this.deps.pool.forwardOut(forward.alias, forward.remoteHost, forward.remotePort);
3949
+ /**
3950
+ * Ask for the host's DEDICATED forward connection: forwarding traffic is
3951
+ * long-lived and heavy, and multiplexed onto the shared connection it would
3952
+ * queue ahead of exec/SFTP channels. The pool falls back on its own when the
3953
+ * server refuses the extra connection, and tells us which one was used so
3954
+ * the row can say so.
3955
+ */
3956
+ const opened = await this.deps.pool.forwardOut(forward.alias, forward.remoteHost, forward.remotePort, 0, { dedicated: true });
3957
+ channel = opened.channel;
3958
+ forward.transport = opened.dedicated ? "dedicated" : "shared";
2250
3959
  } catch (error) {
2251
3960
  forward.lastError = messageOf$2(error);
2252
3961
  this.log("warn", `forward ${forward.id} -> ${forward.remoteHost}:${forward.remotePort} failed: ${forward.lastError}`);
@@ -2313,6 +4022,7 @@ var ForwardManager = class {
2313
4022
  bytesIn: forward.bytesIn,
2314
4023
  bytesOut: forward.bytesOut,
2315
4024
  ...forward.lastError === void 0 ? {} : { lastError: forward.lastError },
4025
+ ...forward.transport === void 0 ? {} : { transport: forward.transport },
2316
4026
  startedAt: forward.startedAt
2317
4027
  };
2318
4028
  }
@@ -2666,7 +4376,7 @@ async function bootstrap(pool, store, alias) {
2666
4376
  kind: "key",
2667
4377
  keyPath: privatePath
2668
4378
  } });
2669
- pool.drop(alias);
4379
+ pool.forget(alias);
2670
4380
  const check = await pool.test(alias);
2671
4381
  if (!check.ok) throw new Error(`key installed but key login failed: ${check.error} (password entry was already flipped; fix the key or re-enter the password)`);
2672
4382
  return {
@@ -2681,8 +4391,12 @@ async function bootstrap(pool, store, alias) {
2681
4391
  /**
2682
4392
  * One-shot importers: ~/.ssh/config and the existing dsh-ssh.json. Both only
2683
4393
  * READ the source and produce payloads for our own store — no runtime coupling.
2684
- * P0 supports direct key/password hosts only; jump/proxy/agent entries are
2685
- * reported as skipped with reasons.
4394
+ * Hosts are direct key hosts; the egress half of a `Host` block (`ProxyJump` /
4395
+ * `ProxyCommand`) is mapped onto the store's `proxy` field when it names
4396
+ * something this import actually produces, and refused BY NAME when it names a
4397
+ * form this plugin cannot dial (multi-hop, a shell command, a jump host that is
4398
+ * not part of the config). A silent skip used to be the answer to all of them;
4399
+ * "one hop, from this same config" is the honest boundary.
2686
4400
  */
2687
4401
  /** Expand a leading ~ to the user home. */
2688
4402
  function expandHome(path) {
@@ -2702,9 +4416,89 @@ function validPort(value) {
2702
4416
  if (!Number.isInteger(port) || port < 1 || port > 65535) return void 0;
2703
4417
  return port;
2704
4418
  }
4419
+ /** `ProxyJump none` / `ProxyCommand none` is OpenSSH for "explicitly no proxy". */
4420
+ function isNone(value) {
4421
+ return value.trim().toLowerCase() === "none";
4422
+ }
4423
+ /**
4424
+ * Index every name an imported host answers to: its alias and its `HostName`.
4425
+ *
4426
+ * `ProxyJump bastion` may name the `Host bastion` alias or the literal hostname
4427
+ * it resolves to, so both are accepted; a name with no host behind it in THIS
4428
+ * config cannot become a `viaAlias` (the stored setting would dangle).
4429
+ */
4430
+ function nameIndex(candidates) {
4431
+ const index = /* @__PURE__ */ new Map();
4432
+ for (const candidate of candidates) {
4433
+ index.set(candidate.alias, candidate.alias);
4434
+ index.set(candidate.alias.toLowerCase(), candidate.alias);
4435
+ index.set(candidate.hostname, candidate.alias);
4436
+ index.set(candidate.hostname.toLowerCase(), candidate.alias);
4437
+ }
4438
+ return index;
4439
+ }
4440
+ /** Resolve one jump host name against the hosts this import creates. */
4441
+ function resolveJump(self, name, index) {
4442
+ const viaAlias = index.get(name) ?? index.get(name.toLowerCase());
4443
+ if (viaAlias === void 0) return {
4444
+ ok: false,
4445
+ reason: `jump host '${name}' is not imported by this config — a jump host must be one of its Host entries`
4446
+ };
4447
+ if (viaAlias === self) return {
4448
+ ok: false,
4449
+ reason: `jump host '${name}' is this host itself`
4450
+ };
4451
+ return {
4452
+ ok: true,
4453
+ proxy: {
4454
+ mode: "jump",
4455
+ jump: { viaAlias }
4456
+ }
4457
+ };
4458
+ }
4459
+ /**
4460
+ * Turn one block's egress directive into the store's proxy decision.
4461
+ *
4462
+ * Precedence matches OpenSSH (a set `ProxyJump` wins over `ProxyCommand`), and
4463
+ * everything unusable keeps the PARSER's own reason so the report says what to
4464
+ * fix ("only one hop", "not supported program") instead of a generic skip.
4465
+ */
4466
+ function resolveProxy(self, fields, index) {
4467
+ const jump = fields.get("proxyjump");
4468
+ if (jump !== void 0) {
4469
+ if (isNone(jump)) return { ok: true };
4470
+ const parsed = parseProxyJump(jump);
4471
+ if (!parsed.ok) return {
4472
+ ok: false,
4473
+ reason: parsed.reason
4474
+ };
4475
+ return resolveJump(self, parsed.target.host, index);
4476
+ }
4477
+ const command = fields.get("proxycommand");
4478
+ if (command !== void 0) {
4479
+ if (isNone(command)) return { ok: true };
4480
+ const plan = parseProxyCommand(command);
4481
+ if (plan.kind === "proxy") return {
4482
+ ok: true,
4483
+ proxy: {
4484
+ mode: "proxy",
4485
+ proxy: {
4486
+ kind: plan.proxy.kind,
4487
+ host: plan.proxy.host,
4488
+ port: plan.proxy.port
4489
+ }
4490
+ }
4491
+ };
4492
+ if (plan.kind === "jump") return resolveJump(self, plan.target.host, index);
4493
+ return {
4494
+ ok: false,
4495
+ reason: plan.reason
4496
+ };
4497
+ }
4498
+ return { ok: true };
4499
+ }
2705
4500
  /** Parse OpenSSH client config text into host payloads. */
2706
4501
  function parseSshConfig(text) {
2707
- const payloads = [];
2708
4502
  const skipped = [];
2709
4503
  const blocks = [];
2710
4504
  let current;
@@ -2735,6 +4529,7 @@ function parseSshConfig(text) {
2735
4529
  });
2736
4530
  else if (current !== void 0 && !current.fields.has(key)) current.fields.set(key, value);
2737
4531
  }
4532
+ const candidates = [];
2738
4533
  for (const block of blocks) {
2739
4534
  const concrete = block.patterns.filter((pattern) => pattern !== "" && !/[*?!]/.test(pattern));
2740
4535
  const special = block.patterns.filter((pattern) => pattern !== "" && /[*?!]/.test(pattern));
@@ -2749,13 +4544,6 @@ function parseSshConfig(text) {
2749
4544
  });
2750
4545
  continue;
2751
4546
  }
2752
- if (block.fields.has("proxyjump") || block.fields.has("proxycommand")) {
2753
- for (const alias of concrete) skipped.push({
2754
- alias,
2755
- reason: "proxyJump/proxyCommand needs P1 (direct hosts only in P0)"
2756
- });
2757
- continue;
2758
- }
2759
4547
  const rawPort = block.fields.get("port");
2760
4548
  const port = rawPort === void 0 ? 22 : validPort(rawPort);
2761
4549
  const identityFile = block.fields.get("identityfile")?.split(/\s+/)[0];
@@ -2782,18 +4570,39 @@ function parseSshConfig(text) {
2782
4570
  });
2783
4571
  continue;
2784
4572
  }
2785
- payloads.push({
4573
+ candidates.push({
2786
4574
  alias,
2787
- host: block.fields.get("hostname") ?? alias,
4575
+ hostname: block.fields.get("hostname") ?? alias,
2788
4576
  port,
2789
4577
  user,
2790
- auth: {
2791
- kind: "key",
2792
- keyPath: expandHome(identityFile)
2793
- },
2794
- tags: ["imported:ssh-config"]
4578
+ identityFile,
4579
+ fields: block.fields
4580
+ });
4581
+ }
4582
+ }
4583
+ const index = nameIndex(candidates);
4584
+ const payloads = [];
4585
+ for (const candidate of candidates) {
4586
+ const resolution = resolveProxy(candidate.alias, candidate.fields, index);
4587
+ if (!resolution.ok) {
4588
+ skipped.push({
4589
+ alias: candidate.alias,
4590
+ reason: resolution.reason
2795
4591
  });
4592
+ continue;
2796
4593
  }
4594
+ payloads.push({
4595
+ alias: candidate.alias,
4596
+ host: candidate.hostname,
4597
+ port: candidate.port,
4598
+ user: candidate.user,
4599
+ auth: {
4600
+ kind: "key",
4601
+ keyPath: expandHome(candidate.identityFile)
4602
+ },
4603
+ tags: ["imported:ssh-config"],
4604
+ ...resolution.proxy === void 0 ? {} : { proxy: resolution.proxy }
4605
+ });
2797
4606
  }
2798
4607
  return {
2799
4608
  payloads,
@@ -2831,7 +4640,7 @@ function migrateDshSsh(home = dshHome()) {
2831
4640
  if (hasProxy) {
2832
4641
  skipped.push({
2833
4642
  alias,
2834
- reason: "proxyJump/proxyCommand needs P1 (direct hosts only in P0)"
4643
+ reason: "proxyJump/proxyCommand in dsh-ssh.json is not mapped — import from ~/.ssh/config instead"
2835
4644
  });
2836
4645
  continue;
2837
4646
  }
@@ -3980,6 +5789,24 @@ function bodyAliasOf(value) {
3980
5789
  return typeof alias === "string" && alias !== "" ? alias : null;
3981
5790
  }
3982
5791
  /**
5792
+ * Which channel budget an exec request asks for, from the two accepted spellings.
5793
+ *
5794
+ * `lane` is the current field (`'network'` for fetch/pull/push, `'git'` for git
5795
+ * commands — reads and local writes alike) and `network: true` is the flag from
5796
+ * before the git budget existed — kept because a browser tab can run an OLD client
5797
+ * bundle against this host. An explicit `lane` wins when both are sent, and
5798
+ * anything else (a typo, `'exec'`, a number) is IGNORED so a bad value can never
5799
+ * move traffic onto a smaller budget than the caller meant.
5800
+ *
5801
+ * An empty object means "no lane": the command spends the shared exec budget,
5802
+ * which is what every caller that predates the lanes gets.
5803
+ */
5804
+ function execLaneOf(body) {
5805
+ if (body.lane === "network" || body.lane === "git") return { lane: body.lane };
5806
+ if (body.network === true) return { lane: "network" };
5807
+ return {};
5808
+ }
5809
+ /**
3983
5810
  * A caller mistake the route can name: well-formed HTTP, unusable payload.
3984
5811
  *
3985
5812
  * `/files` used to throw plain Errors for missing fields and map EVERY failure
@@ -4321,17 +6148,30 @@ function makeRoutes(deps) {
4321
6148
  });
4322
6149
  res.on("close", () => stop());
4323
6150
  };
4324
- /** Apply parsed import payloads; per-entry errors become skips. */
6151
+ /**
6152
+ * Apply parsed import payloads; per-entry errors become skips.
6153
+ *
6154
+ * Two rounds, jump rows LAST, because a `jump` decision names ANOTHER host and
6155
+ * `store.create` refuses a `viaAlias` that is not stored yet. Payload order is
6156
+ * the order of the source file, which is not a dependency order: a config that
6157
+ * writes `Host target` (`ProxyJump bastion`) before `Host bastion` used to
6158
+ * import the bastion and silently drop the host that needs it, reported only as
6159
+ * `proxy.jump.viaAlias: unknown host alias bastion`. One hop is the supported
6160
+ * shape (a jump host is never itself a jump host), so two rounds always
6161
+ * suffice; whatever is still unknown in round two is a host this import did
6162
+ * not create (it was skipped for its own reason, which the report already
6163
+ * carries), and stays a skip with the store's own wording.
6164
+ */
4325
6165
  const applyImport = (parsed) => {
4326
6166
  const imported = [];
4327
6167
  const skipped = [...parsed.skipped];
4328
- for (const payload of parsed.payloads) {
6168
+ const create = (payload) => {
4329
6169
  if (store.get(payload.alias) !== void 0) {
4330
6170
  skipped.push({
4331
6171
  alias: payload.alias,
4332
6172
  reason: "alias already exists"
4333
6173
  });
4334
- continue;
6174
+ return;
4335
6175
  }
4336
6176
  try {
4337
6177
  store.create(payload);
@@ -4342,7 +6182,9 @@ function makeRoutes(deps) {
4342
6182
  reason: error instanceof Error ? error.message : String(error)
4343
6183
  });
4344
6184
  }
4345
- }
6185
+ };
6186
+ for (const payload of parsed.payloads.filter((entry) => entry.proxy?.mode !== "jump")) create(payload);
6187
+ for (const payload of parsed.payloads.filter((entry) => entry.proxy?.mode === "jump")) create(payload);
4346
6188
  return {
4347
6189
  imported,
4348
6190
  skipped
@@ -4414,11 +6256,11 @@ function makeRoutes(deps) {
4414
6256
  return;
4415
6257
  }
4416
6258
  try {
6259
+ const entry = store.update(alias, body);
4417
6260
  pool.forget(alias);
4418
6261
  monitor.forget(alias);
4419
6262
  forgetProcesses(alias);
4420
6263
  worlds.dropHost(alias).catch(() => void 0);
4421
- const entry = store.update(alias, body);
4422
6264
  writeJson(res, 200, { host: store.summarize(entry) });
4423
6265
  } catch (error) {
4424
6266
  writeJson(res, (error instanceof Error ? error.message : "").startsWith("unknown host alias") ? 404 : 400, { error: error instanceof Error ? error.message : String(error) });
@@ -4440,6 +6282,30 @@ function makeRoutes(deps) {
4440
6282
  writeJson(res, 200, { connections: pool.status() });
4441
6283
  }
4442
6284
  },
6285
+ {
6286
+ kind: "exact",
6287
+ path: REMOTE_API.connections,
6288
+ handler: async (req, res) => {
6289
+ if (!isLoopbackRequest(req)) {
6290
+ writeJson(res, 403, { error: "forbidden: loopback-only" });
6291
+ return;
6292
+ }
6293
+ if (req.method !== "GET") {
6294
+ writeJson(res, 405, { error: `method not allowed: ${req.method}` });
6295
+ return;
6296
+ }
6297
+ try {
6298
+ const hosts = pool.stats();
6299
+ await Promise.all(hosts.map(async (host) => {
6300
+ const lane = await worlds.helperLane(host.alias).catch(() => void 0);
6301
+ if (lane !== void 0) host.connections.helper = lane;
6302
+ }));
6303
+ writeJson(res, 200, { hosts });
6304
+ } catch (error) {
6305
+ writeRouteError(res, error);
6306
+ }
6307
+ }
6308
+ },
4443
6309
  {
4444
6310
  kind: "exact",
4445
6311
  path: REMOTE_API.test,
@@ -4509,6 +6375,7 @@ function makeRoutes(deps) {
4509
6375
  return;
4510
6376
  }
4511
6377
  const timeoutMs = clampExecTimeout(body.timeoutMs);
6378
+ const lane = execLaneOf(body);
4512
6379
  /** The client closed the request: its response is never read. */
4513
6380
  let clientGone = false;
4514
6381
  /** The client asked to stop: kill the remote even if the read is still opening. */
@@ -4539,6 +6406,7 @@ function makeRoutes(deps) {
4539
6406
  try {
4540
6407
  const result = await pool.exec(body.alias, body.command, {
4541
6408
  ...timeoutMs === void 0 ? {} : { timeoutMs },
6409
+ ...lane,
4542
6410
  onCancel: (handle) => {
4543
6411
  cancel = handle;
4544
6412
  if (cancelRequested && !cancelSent) {
@@ -4573,6 +6441,7 @@ function makeRoutes(deps) {
4573
6441
  return;
4574
6442
  }
4575
6443
  const timeoutMs = clampExecTimeout(body.timeoutMs);
6444
+ const lane = execLaneOf(body);
4576
6445
  res.writeHead(200, {
4577
6446
  "Content-Type": "text/event-stream; charset=utf-8",
4578
6447
  "Cache-Control": "no-cache, no-transform",
@@ -4641,6 +6510,7 @@ function makeRoutes(deps) {
4641
6510
  try {
4642
6511
  const result = await pool.exec(body.alias, body.command, {
4643
6512
  ...timeoutMs === void 0 ? {} : { timeoutMs },
6513
+ ...lane,
4644
6514
  onData: (stream, text) => {
4645
6515
  if (outputClosed || sent >= FORWARD_CAP) return;
4646
6516
  sent += Buffer.byteLength(text, "utf8");
@@ -5151,6 +7021,40 @@ function makeRoutes(deps) {
5151
7021
  }
5152
7022
  }
5153
7023
  },
7024
+ {
7025
+ kind: "exact",
7026
+ path: REMOTE_API.proxySettings,
7027
+ handler: async (req, res) => {
7028
+ if (!isLoopbackRequest(req)) {
7029
+ writeJson(res, 403, { error: "forbidden: loopback-only" });
7030
+ return;
7031
+ }
7032
+ const method = req.method ?? "GET";
7033
+ if (method === "GET") {
7034
+ try {
7035
+ writeJson(res, 200, { settings: store.getDefaultProxy() });
7036
+ } catch (error) {
7037
+ writeStoreError(res, error);
7038
+ }
7039
+ return;
7040
+ }
7041
+ if (method !== "POST" && method !== "PATCH") {
7042
+ writeJson(res, 405, { error: `method not allowed: ${method}` });
7043
+ return;
7044
+ }
7045
+ const read = await readBodyOrError(req, res, { objectOnly: true });
7046
+ if (!read.ok) return;
7047
+ try {
7048
+ writeJson(res, 200, { settings: store.patchDefaultProxy(read.body ?? {}) });
7049
+ } catch (error) {
7050
+ if (isStoreError(error)) {
7051
+ writeStoreError(res, error);
7052
+ return;
7053
+ }
7054
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
7055
+ }
7056
+ }
7057
+ },
5154
7058
  {
5155
7059
  kind: "exact",
5156
7060
  path: REMOTE_API.deploy,
@@ -5792,13 +7696,24 @@ function excludeDirNames(dirs) {
5792
7696
  /**
5793
7697
  * New files git is not tracking yet (the ones a session usually creates).
5794
7698
  *
7699
+ * `--directory` is the load-bearing flag. Without it git descends into every
7700
+ * untracked directory and prints one path per FILE: measured on the reference
7701
+ * monorepo that is 11.25s warm, and on a cold AOSP checkout past a minute. With
7702
+ * it, an untracked directory is reported ONCE as `dir/` (trailing slash) and git
7703
+ * stops descending — a build tree or an un-ignored dependency tree costs one
7704
+ * record instead of thousands of `stat`s. The scan still has to walk the tracked
7705
+ * part of the tree, but the expensive half is exactly the part that is skipped.
7706
+ *
7707
+ * The semantic cost is that the answer now names directories; the caller expands
7708
+ * the ones it still wants files for with {@link untrackedExpandCommand}, within
7709
+ * bounds of its own (see `UNTRACKED_EXPAND_DIRS` in `recorder.ts`). A file that
7710
+ * git reports directly is already the final answer.
7711
+ *
5795
7712
  * The exclusions are pushed down as pathspecs (`:(exclude)out`) rather than
5796
7713
  * filtered after the fact, so those paths never cross the wire and never enter
5797
7714
  * the 500-row cap. Measured on a tree with 3000 build outputs + 300 sources:
5798
7715
  * 3300 records / 61.5 KB unfiltered versus 300 records / 6.8 KB with two
5799
- * exclusions — the walk itself costs the same either way (git still descends
5800
- * those directories), so the win is wire bytes, parse time and the read budget,
5801
- * not scan latency.
7716
+ * exclusions.
5802
7717
  *
5803
7718
  * @param root - remote absolute POSIX directory (the session cwd).
5804
7719
  * @param excludeDirs - directory names to leave out (see {@link excludeDirNames}).
@@ -5810,7 +7725,49 @@ function untrackedCommand(root, excludeDirs = []) {
5810
7725
  ".",
5811
7726
  ...excludeDirNames(excludeDirs).map((name) => shq(`:(exclude)${name}`))
5812
7727
  ].join(" ");
5813
- return [cdLine(root), `git ls-files --others --exclude-standard -z ${pathspec}`].join("\n");
7728
+ return [cdLine(root), `git ls-files --others --exclude-standard -z --directory ${pathspec}`].join("\n");
7729
+ }
7730
+ /**
7731
+ * Whether a `--directory` record names a collapsed DIRECTORY.
7732
+ *
7733
+ * git marks one with a trailing slash; a record without it is a file, which is
7734
+ * already the final answer and must not be expanded again.
7735
+ */
7736
+ function isUntrackedDirectoryPath(path) {
7737
+ return path.endsWith("/");
7738
+ }
7739
+ /**
7740
+ * List the files inside EVERY directory a {@link untrackedCommand} walk
7741
+ * collapsed, in ONE command.
7742
+ *
7743
+ * Same walk, same exclusions, minus `--directory`: the caller gets file paths
7744
+ * again. One command for all of them on purpose — git also collapses directories
7745
+ * that hold nothing but IGNORED files (`build/` full of gitignored output) and
7746
+ * empty ones, so a per-directory loop would spend a whole round trip (and one of
7747
+ * the expansion slots) proving that such a directory has no visible file inside.
7748
+ * Batched, an empty directory costs nothing and cannot push a real one out of
7749
+ * the slot budget.
7750
+ *
7751
+ * Every directory comes from git's own output, but each still crosses a shell, so
7752
+ * each goes through {@link shq} — a directory named `it's a 目录` is one quoted
7753
+ * argument, never a second command or a flag.
7754
+ *
7755
+ * The trailing slash the fast walk adds is dropped: the pathspec names the
7756
+ * directory either way, and a bare path keeps this builder from ever emitting
7757
+ * `-- ''` (which would mean "the whole repository").
7758
+ *
7759
+ * @param root - remote absolute POSIX directory (the session cwd).
7760
+ * @param dirs - collapsed directories from {@link untrackedCommand}, with or
7761
+ * without their trailing slashes.
7762
+ * @param excludeDirs - the same exclusions the fast walk used (nested build
7763
+ * output inside a collapsed directory must stay out too).
7764
+ */
7765
+ function untrackedExpandCommand(root, dirs, excludeDirs = []) {
7766
+ const targets = dirs.map((dir) => dir.replace(/\/+$/, "")).filter((dir) => dir !== "");
7767
+ if (targets.length === 0) throw new Error("untracked expand needs at least one directory path");
7768
+ const excludes = excludeDirNames(excludeDirs).map((name) => shq(`:(exclude)${name}`));
7769
+ const pathspec = [...targets.map((dir) => shq(dir)), ...excludes].join(" ");
7770
+ return [cdLine(root), `git ls-files --others --exclude-standard -z -- ${pathspec}`].join("\n");
5814
7771
  }
5815
7772
  /**
5816
7773
  * Parse `git status --porcelain -z -uno` output.
@@ -6499,8 +8456,6 @@ function filePatch(displayPath, hunks) {
6499
8456
  }
6500
8457
  return `${out.join("\n")}\n`;
6501
8458
  }
6502
- //#endregion
6503
- //#region src/changes/recorder.ts
6504
8459
  /**
6505
8460
  * Map a scan entry onto the panel's vocabulary.
6506
8461
  *
@@ -7016,6 +8971,7 @@ var SessionChanges = class {
7016
8971
  ledger.adoptedSubdir = false;
7017
8972
  ledger.tracked = [];
7018
8973
  ledger.untracked = void 0;
8974
+ ledger.untrackedTruncated = false;
7019
8975
  ledger.untrackedAt = 0;
7020
8976
  ledger.untrackedMs = void 0;
7021
8977
  ledger.scanMs = void 0;
@@ -7097,6 +9053,7 @@ var SessionChanges = class {
7097
9053
  subdir: "",
7098
9054
  tracked: [],
7099
9055
  untracked: void 0,
9056
+ untrackedTruncated: false,
7100
9057
  untrackedAt: 0,
7101
9058
  untrackedMs: void 0,
7102
9059
  scanMs: void 0,
@@ -7180,7 +9137,7 @@ var SessionChanges = class {
7180
9137
  const entries = [...merged.values()].sort((left, right) => left.path.localeCompare(right.path));
7181
9138
  const cap = this.deps.maxFiles ?? 500;
7182
9139
  const listed = entries.slice(0, cap);
7183
- const truncated = entries.length > cap;
9140
+ const truncated = entries.length > cap || ledger.untrackedTruncated;
7184
9141
  if (!ledger.baselineTaken) {
7185
9142
  const first = await this.readPaths(ledger, listed.map((entry) => entry.path), "worktree");
7186
9143
  if (ledger.disposed || ledger.root !== root) return;
@@ -7623,26 +9580,39 @@ var SessionChanges = class {
7623
9580
  * runs twice at once, and only runs again after {@link untrackedCadence}. A
7624
9581
  * repository that cannot answer inside {@link untrackedBudget} is written off
7625
9582
  * for the session (`untrackedGivenUp`) rather than retried every turn.
9583
+ *
9584
+ * Two phases since the scan learned `--directory`: one fast walk that collapses
9585
+ * untracked directories (`build/` instead of 3000 paths) and then a BOUNDED
9586
+ * expansion of the collapsed entries, because the panel's contract is a list of
9587
+ * FILES. A walk that already answered with files expands nothing at all.
7626
9588
  */
7627
9589
  async kickUntracked(ledger) {
7628
9590
  if (ledger.disposed || ledger.untrackedGivenUp || ledger.untrackedJob !== void 0) return;
7629
9591
  if (ledger.untracked !== void 0 && Date.now() - ledger.untrackedAt < this.untrackedCadence(ledger)) return;
7630
9592
  const root = ledger.root;
7631
9593
  ledger.untrackedAt = Date.now();
9594
+ const deadline = ledger.untrackedAt + this.untrackedBudget();
7632
9595
  ledger.untrackedJob = (async () => {
7633
9596
  const started = Date.now();
7634
- const scan = await this.run(ledger.alias, untrackedCommand(root, this.excludedDirs()), this.untrackedBudget());
7635
- ledger.untrackedMs = Date.now() - started;
9597
+ const excluded = this.excludedDirs();
9598
+ const scan = await this.run(ledger.alias, untrackedCommand(root, excluded), Math.max(1, deadline - Date.now()));
7636
9599
  if (ledger.disposed) return;
7637
9600
  if (ledger.root !== root) return;
7638
9601
  if (!scan.ok) {
9602
+ ledger.untrackedMs = Date.now() - started;
7639
9603
  ledger.untrackedGivenUp = true;
9604
+ ledger.untrackedTruncated = false;
7640
9605
  ledger.untrackedFailure = scan.reason;
7641
9606
  this.warn(`untracked scan unusable (${scan.reason}); new files will not be listed`);
7642
9607
  return;
7643
9608
  }
7644
9609
  ledger.untrackedFailure = void 0;
7645
- ledger.untracked = parseUntrackedZ(scan.stdout);
9610
+ const expanded = await this.expandUntracked(ledger, root, parseUntrackedZ(scan.stdout), excluded, deadline);
9611
+ if (ledger.disposed) return;
9612
+ if (ledger.root !== root) return;
9613
+ ledger.untrackedMs = Date.now() - started;
9614
+ ledger.untracked = expanded.entries;
9615
+ ledger.untrackedTruncated = expanded.truncated;
7646
9616
  await this.absorbPreExisting(ledger);
7647
9617
  await this.publish(ledger, true);
7648
9618
  })().catch((error) => this.warn(`untracked scan failed: ${messageOf(error)}`)).finally(() => {
@@ -7650,6 +9620,73 @@ var SessionChanges = class {
7650
9620
  });
7651
9621
  }
7652
9622
  /**
9623
+ * Turn the fast walk's collapsed directories back into files, within bounds.
9624
+ *
9625
+ * Bounded THREE ways, because every expansion is another `git ls-files` on the
9626
+ * same shared connection and the scan runs in the background where nobody is
9627
+ * watching:
9628
+ *
9629
+ * - at most {@link UNTRACKED_EXPAND_DIRS} directories, sorted first so the
9630
+ * choice is deterministic (a rescan of an unchanged tree expands the same
9631
+ * ones, and the gate can pin exactly which);
9632
+ * - the same file cap the panel lists (`maxFiles`, 500 by default), so one
9633
+ * huge directory cannot push the list past what is displayable;
9634
+ * - the fast walk's own deadline: when it runs out the phase stops.
9635
+ *
9636
+ * Hitting any of them — or an expansion that fails — marks the result
9637
+ * `truncated` instead of returning a short list silently. A failed expansion is
9638
+ * NOT `untrackedGivenUp`: the fast walk answered, so new-file detection still
9639
+ * works; only part of it is missing.
9640
+ *
9641
+ * @returns the file entries (walk files + expanded ones) and whether the list
9642
+ * is incomplete.
9643
+ */
9644
+ async expandUntracked(ledger, root, walked, excludeDirs, deadline) {
9645
+ const entries = walked.filter((entry) => !isUntrackedDirectoryPath(entry.path));
9646
+ const dirs = walked.filter((entry) => isUntrackedDirectoryPath(entry.path)).map((entry) => entry.path.replace(/\/+$/, "")).filter((path) => path !== "").sort();
9647
+ if (dirs.length === 0) return {
9648
+ entries,
9649
+ truncated: false
9650
+ };
9651
+ const cap = this.deps.maxFiles ?? 500;
9652
+ let truncated = dirs.length > 20;
9653
+ const pending = dirs.slice(0, 20);
9654
+ const remaining = deadline - Date.now();
9655
+ if (remaining <= 0) {
9656
+ this.warn(`untracked expansion ran out of its budget before asking about ${pending.length} directories`);
9657
+ return {
9658
+ entries,
9659
+ truncated: true
9660
+ };
9661
+ }
9662
+ const result = await this.run(ledger.alias, untrackedExpandCommand(root, pending, excludeDirs), remaining);
9663
+ if (ledger.disposed || ledger.root !== root) return {
9664
+ entries,
9665
+ truncated: true
9666
+ };
9667
+ if (!result.ok) {
9668
+ this.warn(`expanding ${pending.length} untracked directories failed (${result.reason}); new files under them are not listed`);
9669
+ return {
9670
+ entries,
9671
+ truncated: true
9672
+ };
9673
+ }
9674
+ const seen = new Set(entries.map((entry) => entry.path));
9675
+ for (const entry of parseUntrackedZ(result.stdout)) {
9676
+ if (seen.has(entry.path)) continue;
9677
+ seen.add(entry.path);
9678
+ entries.push(entry);
9679
+ if (entries.length >= cap) {
9680
+ truncated = true;
9681
+ break;
9682
+ }
9683
+ }
9684
+ return {
9685
+ entries,
9686
+ truncated
9687
+ };
9688
+ }
9689
+ /**
7653
9690
  * How long before the untracked scan may run again.
7654
9691
  *
7655
9692
  * Self-tuning on purpose: the same command costs ~0.2s in a small repository
@@ -7725,10 +9762,23 @@ var SessionChanges = class {
7725
9762
  }
7726
9763
  return parseReads(result.stdout);
7727
9764
  }
7728
- /** Run one command on the host, normalizing failure into a reason string. */
9765
+ /**
9766
+ * Run one command on the host, normalizing failure into a reason string.
9767
+ *
9768
+ * Every command this ledger issues is a git command (a repository read: `git
9769
+ * status`, the untracked walk, its expansion, the file-content reads — the
9770
+ * recorder never mutates). So they all spend the host's git-command budget
9771
+ * (`lane: 'git'`) instead of a shared exec slot: these scans run in the HOST
9772
+ * process while the user is working, and a 300-second `git status` must not be
9773
+ * the reason a monitor sample, the process panel or an agent tool answers
9774
+ * "host is busy".
9775
+ */
7729
9776
  async run(alias, command, budget = this.execBudget()) {
7730
9777
  try {
7731
- const call = this.deps.pool.exec(alias, command, { timeoutMs: budget });
9778
+ const call = this.deps.pool.exec(alias, command, {
9779
+ timeoutMs: budget,
9780
+ lane: "git"
9781
+ });
7732
9782
  const result = await this.withWatchdog(call, budget + Math.min(WATCHDOG_GRACE_MS, budget));
7733
9783
  if (result === WATCHDOG_FIRED) return {
7734
9784
  ok: false,
@@ -7765,19 +9815,24 @@ var SessionChanges = class {
7765
9815
  if (override !== void 0 && Number.isFinite(override) && override > 0) return override;
7766
9816
  return this.budget(this.deps.timeouts().gitMs, 5e3, 6e4);
7767
9817
  }
7768
- /** The untracked scan gets its own, more generous budget. */
7769
9818
  /**
7770
- * The untracked scan gets its own, much more generous budget.
7771
- *
7772
- * Three minutes is a deliberate choice for a monorepo: the walk is proportional
7773
- * to the whole checkout, not to the session, and the reference AOSP tree has
7774
- * been measured past a minute cold. Waiting is acceptable here because the
7775
- * scan runs in the background and the tracked changes are already on screen;
7776
- * giving up early is not, because the files a session creates with a shell
7777
- * command are visible ONLY through this scan.
9819
+ * The untracked scan gets its own, more generous budget — one minute.
9820
+ *
9821
+ * The walk is proportional to the whole checkout, not to the session, so it
9822
+ * cannot use the ordinary git budget. It used to be three minutes; that ceiling
9823
+ * was set before the scan learned `--directory`, when a monorepo's answer really
9824
+ * could take that long. Now the fast walk collapses whole directories, so a
9825
+ * minute is already several times the useful wait, and every second past it is
9826
+ * spent holding an exec channel on the SHARED connection while the tree is
9827
+ * still being walked for nothing. Past a minute the honest answer is "this host
9828
+ * cannot enumerate new files quickly enough" — `untrackedFailure` says so and the
9829
+ * panel offers a retry, which is the same contract as before, just cut shorter.
9830
+ *
9831
+ * The floor (10s) is untouched: a small repository must never be cut off by a
9832
+ * tiny configured `gitMs`.
7778
9833
  */
7779
9834
  untrackedBudget() {
7780
- return this.deps.untrackedBudgetMs ?? this.budget(this.deps.timeouts().gitMs, 1e4, 18e4);
9835
+ return this.deps.untrackedBudgetMs ?? this.budget(this.deps.timeouts().gitMs, 1e4, 6e4);
7781
9836
  }
7782
9837
  /**
7783
9838
  * The exclusions this ledger scans with, normalized once per call.
@@ -7835,11 +9890,23 @@ function toAgentHostRow(host) {
7835
9890
  managedKey: host.managedKey,
7836
9891
  ...host.description !== void 0 ? { description: host.description } : {},
7837
9892
  tags: [...host.tags],
9893
+ proxy: host.proxy,
7838
9894
  createdAt: host.createdAt,
7839
9895
  updatedAt: host.updatedAt
7840
9896
  };
7841
9897
  }
7842
9898
  /**
9899
+ * One-line description of a host's effective route, for the agent table.
9900
+ *
9901
+ * `problem` is part of the value (not a separate column): a host whose jump target
9902
+ * was deleted is still listed, and the caller must see why it would fail.
9903
+ */
9904
+ function proxyLabel(proxy) {
9905
+ const target = proxy.target === void 0 ? "" : ` ${proxy.target.host}:${proxy.target.port}`;
9906
+ const route = proxy.mode === "proxy" ? `proxy${target}` : proxy.mode === "jump" ? `jump ${proxy.jumpVia ?? "?"}` : proxy.mode;
9907
+ return proxy.problem === void 0 ? route : `${route} (problem: ${proxy.problem})`;
9908
+ }
9909
+ /**
7843
9910
  * Render the host table.
7844
9911
  *
7845
9912
  * An empty list has TWO very different causes and they used to share one
@@ -7850,8 +9917,8 @@ function toAgentHostRow(host) {
7850
9917
  function renderHosts(hosts, query) {
7851
9918
  if (hosts.length === 0) return query === void 0 || query.trim() === "" ? "no remote hosts configured (add one in the Remote sidebar tab first)" : `no remote host matches "${query}" — hosts are configured, the query just filtered them all out`;
7852
9919
  return [
7853
- "alias | host | port | user | auth | key | tags | description",
7854
- "--- | --- | --- | --- | --- | --- | --- | ---",
9920
+ "alias | host | port | user | auth | key | proxy | tags | description",
9921
+ "--- | --- | --- | --- | --- | --- | --- | --- | ---",
7855
9922
  ...hosts.map((h) => [
7856
9923
  h.alias,
7857
9924
  h.host,
@@ -7859,6 +9926,7 @@ function renderHosts(hosts, query) {
7859
9926
  h.user,
7860
9927
  h.auth,
7861
9928
  h.auth === "key" ? h.keyReady ? "key-ok" : "key-missing" : "password",
9929
+ proxyLabel(h.proxy),
7862
9930
  h.tags.length > 0 ? h.tags.join(",") : "-",
7863
9931
  h.description ?? ""
7864
9932
  ].join(" | "))
@@ -7941,6 +10009,49 @@ function remoteHostsTool(deps) {
7941
10009
  items: { type: "string" },
7942
10010
  required: true
7943
10011
  },
10012
+ proxy: {
10013
+ type: "object",
10014
+ additionalProperties: false,
10015
+ required: true,
10016
+ properties: {
10017
+ mode: {
10018
+ type: "string",
10019
+ enum: [
10020
+ "inherit",
10021
+ "direct",
10022
+ "proxy",
10023
+ "jump"
10024
+ ],
10025
+ required: true
10026
+ },
10027
+ target: {
10028
+ type: "object",
10029
+ additionalProperties: false,
10030
+ properties: {
10031
+ kind: {
10032
+ type: "string",
10033
+ enum: ["http", "socks5"],
10034
+ required: true
10035
+ },
10036
+ host: {
10037
+ type: "string",
10038
+ required: true
10039
+ },
10040
+ port: {
10041
+ type: "integer",
10042
+ required: true
10043
+ },
10044
+ username: { type: "string" },
10045
+ hasPassword: {
10046
+ type: "boolean",
10047
+ required: true
10048
+ }
10049
+ }
10050
+ },
10051
+ jumpVia: { type: "string" },
10052
+ problem: { type: "string" }
10053
+ }
10054
+ },
7944
10055
  createdAt: {
7945
10056
  type: "integer",
7946
10057
  required: true