dsh-remote-vs 0.27.0 → 0.29.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 (67) hide show
  1. package/README.en.md +159 -23
  2. package/README.md +123 -23
  3. package/lib/client.js +6906 -6619
  4. package/lib/index.js +2014 -67
  5. package/lib/types/changes/recorder.d.ts +119 -2
  6. package/lib/types/client/CodeEditor.d.ts +15 -0
  7. package/lib/types/client/HostsView.d.ts +139 -2
  8. package/lib/types/client/api.d.ts +42 -2
  9. package/lib/types/client/changes/apply-failure.d.ts +41 -0
  10. package/lib/types/client/changes/block-confirm.d.ts +97 -0
  11. package/lib/types/client/changes/diff-outcome.d.ts +56 -0
  12. package/lib/types/client/changes/freshness.d.ts +51 -0
  13. package/lib/types/client/changes/model.d.ts +19 -1
  14. package/lib/types/client/changes/session-diff.d.ts +100 -0
  15. package/lib/types/client/changes/staleness.d.ts +98 -0
  16. package/lib/types/client/changes/turn-reverted.d.ts +82 -0
  17. package/lib/types/client/changes/turn-view.d.ts +131 -0
  18. package/lib/types/client/changes/undo-affordance.d.ts +44 -10
  19. package/lib/types/client/changes/undo-target.d.ts +12 -0
  20. package/lib/types/client/connection.d.ts +28 -1
  21. package/lib/types/client/i18n.d.ts +1 -1
  22. package/lib/types/client/store.d.ts +91 -1
  23. package/lib/types/client/vsc/change-marks.d.ts +21 -0
  24. package/lib/types/forward.d.ts +11 -1
  25. package/lib/types/pool.d.ts +95 -1
  26. package/lib/types/protocol.d.ts +221 -1
  27. package/lib/types/proxy.d.ts +136 -0
  28. package/lib/types/store.d.ts +81 -1
  29. package/lib/types/tools.d.ts +3 -0
  30. package/package.json +1 -1
  31. package/src/changes/recorder.ts +851 -8
  32. package/src/client/CodeEditor.tsx +43 -3
  33. package/src/client/ConnectionStatus.tsx +19 -5
  34. package/src/client/EditorPane.tsx +64 -7
  35. package/src/client/HostsView.tsx +552 -11
  36. package/src/client/PortsView.tsx +16 -0
  37. package/src/client/SettingsHosts.tsx +132 -6
  38. package/src/client/api.ts +60 -3
  39. package/src/client/changes/ChangesDock.tsx +539 -54
  40. package/src/client/changes/apply-failure.ts +73 -0
  41. package/src/client/changes/block-confirm.ts +180 -0
  42. package/src/client/changes/changes.css +45 -0
  43. package/src/client/changes/diff-outcome.ts +97 -0
  44. package/src/client/changes/freshness.ts +68 -0
  45. package/src/client/changes/model.ts +56 -1
  46. package/src/client/changes/session-diff.ts +187 -0
  47. package/src/client/changes/staleness.ts +148 -0
  48. package/src/client/changes/turn-reverted.ts +254 -0
  49. package/src/client/changes/turn-view.ts +195 -0
  50. package/src/client/changes/undo-affordance.ts +295 -63
  51. package/src/client/changes/undo-target.ts +12 -0
  52. package/src/client/connection.ts +76 -2
  53. package/src/client/i18n.ts +204 -4
  54. package/src/client/scm/DiffView.tsx +32 -13
  55. package/src/client/store.tsx +392 -16
  56. package/src/client/vsc/change-marks.ts +21 -0
  57. package/src/client/vsc/preview-document.tsx +4 -1
  58. package/src/client/vsc/vsc.css +6747 -6509
  59. package/src/forward.ts +38 -2
  60. package/src/importers.ts +125 -13
  61. package/src/keygen.ts +8 -1
  62. package/src/pool.ts +422 -27
  63. package/src/protocol.ts +229 -1
  64. package/src/proxy.ts +673 -0
  65. package/src/routes.ts +93 -14
  66. package/src/store.ts +335 -0
  67. package/src/tools.ts +47 -2
package/lib/index.js CHANGED
@@ -4,13 +4,619 @@ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readF
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,8 @@ 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",
411
1256
  /** Current working directory of one live session (click resolution helper). */
412
1257
  sessionCwd: "/api/dsh-remote/session-cwd",
413
1258
  /** What one live session changed on its remote host (the review panel). */
@@ -591,6 +1436,33 @@ var import_lib = require_lib();
591
1436
  /** Idle time after which a pooled connection is closed. */
592
1437
  const IDLE_MS = 1800 * 1e3;
593
1438
  /**
1439
+ * How long a port forward waits for its DEDICATED connection before falling back.
1440
+ *
1441
+ * The dedicated connection is an optimization, so it must never become the reason
1442
+ * a local socket waits: a server that silently DROPS the extra connection (a very
1443
+ * common `MaxStartups` symptom) would otherwise cost the whole connect watchdog
1444
+ * (45s) per forward channel, with the user staring at a hanging page. Three
1445
+ * seconds is plenty for a second handshake to a host that is already reachable
1446
+ * (the shared connection is up by definition); past that, use the shared one and
1447
+ * let the abandoned dial finish in the background.
1448
+ *
1449
+ * Override with DSH_REMOTE_VS_FORWARD_BUDGET_MS (milliseconds, >= 10) so the gate
1450
+ * does not spend three seconds per case.
1451
+ */
1452
+ const FORWARD_DEDICATED_BUDGET_MS = (() => {
1453
+ const raw = Number(process.env.DSH_REMOTE_VS_FORWARD_BUDGET_MS);
1454
+ return Number.isFinite(raw) && raw >= 10 ? raw : 3e3;
1455
+ })();
1456
+ /**
1457
+ * How long a refused/timed-out dedicated forward connection is skipped per alias.
1458
+ *
1459
+ * A browser opens several forward channels per page; retrying the same refused
1460
+ * handshake for every one of them is exactly the waiting we just removed. One
1461
+ * minute covers the burst; `drop(alias)` (host edited/deleted) and a successful
1462
+ * dedicated connection clear it immediately.
1463
+ */
1464
+ const FORWARD_DEDICATED_BLOCK_MS = 6e4;
1465
+ /**
594
1466
  * Connection establishment timeout, including authentication.
595
1467
  *
596
1468
  * This was 15s, which is not a handshake budget so much as a CPU budget: on a
@@ -721,6 +1593,29 @@ var RemotePool = class {
721
1593
  * that refuses extra connections still gets a working terminal.
722
1594
  */
723
1595
  shellConns = /* @__PURE__ */ new Map();
1596
+ /**
1597
+ * Dedicated connections for `ssh -L` port forwards (one per alias).
1598
+ *
1599
+ * The other half of the same argument: a forwarded channel carries arbitrary
1600
+ * TCP (a database, an SSH tunnel, a whole browser page), so it is long-lived
1601
+ * and can move a lot of data. Multiplexed onto the shared connection it would
1602
+ * queue ahead of exec/SFTP channels (SSH has no per-channel priority), and a
1603
+ * remote service that stalls would hold the window `git status` needs. A
1604
+ * terminal already gets its own connection (`shellConns`); forward traffic gets
1605
+ * its own for exactly the same reason.
1606
+ *
1607
+ * Cost: one extra handshake per alias that actually receives a forwarded
1608
+ * connection, plus one held TCP connection while any of its forward channels is
1609
+ * open (the 30-minute idle eviction applies once the last one closes).
1610
+ * `forwardOut` falls back to the shared connection when this one cannot be
1611
+ * established (e.g. the server refuses extra connections), so a forward never
1612
+ * stops working because of it — it only loses the isolation.
1613
+ */
1614
+ forwardConns = /* @__PURE__ */ new Map();
1615
+ /** Aliases whose dedicated-forward downgrade was already logged (once per alias). */
1616
+ forwardFallbackNoted = /* @__PURE__ */ new Set();
1617
+ /** alias -> timestamp until which the dedicated forward connection is skipped. */
1618
+ forwardBlocked = /* @__PURE__ */ new Map();
724
1619
  /** TOFU fingerprints observed this process (alias -> sha256). */
725
1620
  hostKeys = /* @__PURE__ */ new Map();
726
1621
  /** Per-alias `setsid --wait` capability, probed once (see supportsSetsid). */
@@ -740,10 +1635,17 @@ var RemotePool = class {
740
1635
  this.setsidProbes.delete(alias);
741
1636
  this.evictFrom(this.conns, alias);
742
1637
  this.evictFrom(this.shellConns, alias);
1638
+ this.evictFrom(this.forwardConns, alias);
1639
+ this.forwardBlocked.delete(alias);
1640
+ this.forwardFallbackNoted.delete(alias);
743
1641
  }
744
1642
  /** Close every pooled connection. */
745
1643
  dispose() {
746
- for (const alias of /* @__PURE__ */ new Set([...this.conns.keys(), ...this.shellConns.keys()])) this.drop(alias);
1644
+ for (const alias of /* @__PURE__ */ new Set([
1645
+ ...this.conns.keys(),
1646
+ ...this.shellConns.keys(),
1647
+ ...this.forwardConns.keys()
1648
+ ])) this.drop(alias);
747
1649
  }
748
1650
  /**
749
1651
  * Forget one alias's connection HEALTH (host edited/removed), not just its
@@ -765,22 +1667,67 @@ var RemotePool = class {
765
1667
  */
766
1668
  status() {
767
1669
  const aliases = /* @__PURE__ */ new Set([...this.conns.keys(), ...this.health.keys()]);
1670
+ /** The host rows, read ONCE for the whole answer (see `configuredEgress`). */
1671
+ const hosts = /* @__PURE__ */ new Map();
768
1672
  try {
769
- for (const host of this.store.list()) aliases.add(host.alias);
1673
+ for (const host of this.store.list()) {
1674
+ aliases.add(host.alias);
1675
+ hosts.set(host.alias, host);
1676
+ }
770
1677
  } catch {}
771
1678
  return [...aliases].sort().map((alias) => {
772
1679
  const entry = this.health.get(alias);
773
1680
  const pooled = this.conns.get(alias);
1681
+ const egress = this.liveEgress(alias);
1682
+ const configured = egress === void 0 ? this.configuredEgress(alias, hosts.get(alias)) : void 0;
774
1683
  return {
775
1684
  alias,
776
1685
  state: entry?.state ?? "idle",
777
- open: pooled !== void 0 && pooled.connecting === void 0 || this.shellConns.get(alias)?.connecting === void 0 && this.shellConns.has(alias),
1686
+ 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),
778
1687
  ...entry?.okAt === void 0 ? {} : { okAt: entry.okAt },
779
1688
  ...entry?.errorAt === void 0 ? {} : { errorAt: entry.errorAt },
780
- ...entry?.error === void 0 ? {} : { error: entry.error }
1689
+ ...entry?.error === void 0 ? {} : { error: entry.error },
1690
+ ...egress === void 0 ? {} : { egress },
1691
+ ...configured === void 0 ? {} : { configured }
781
1692
  };
782
1693
  });
783
1694
  }
1695
+ /**
1696
+ * The egress of the alias' LIVE connection, whichever class owns it.
1697
+ *
1698
+ * All three classes open through the same resolved route, so the first one
1699
+ * that is up answers for the alias; the shared connection is preferred because
1700
+ * it is the one exec/browse (the surface the chip describes) rides.
1701
+ */
1702
+ liveEgress(alias) {
1703
+ for (const map of [
1704
+ this.conns,
1705
+ this.forwardConns,
1706
+ this.shellConns
1707
+ ]) {
1708
+ const pooled = map.get(alias);
1709
+ if (pooled === void 0 || pooled.connecting !== void 0) continue;
1710
+ if (pooled.egress !== void 0) return pooled.egress;
1711
+ }
1712
+ }
1713
+ /**
1714
+ * The route the stored configuration resolves to, for an alias with NO live
1715
+ * connection. Pure observation, and absorbed: a dangling jump chain or a
1716
+ * half-configured proxy makes `resolveProxy` throw, and a status poll must
1717
+ * answer "the stored route is broken, here is why" instead of failing — the
1718
+ * chip still has to render, and a 500 would hide the reason it exists to show.
1719
+ */
1720
+ configuredEgress(alias, host) {
1721
+ if (host === void 0) return void 0;
1722
+ try {
1723
+ return egressOf(this.store.resolveProxy(alias), host);
1724
+ } catch (error) {
1725
+ return {
1726
+ ...storedEgress(host),
1727
+ problem: messageOf$3(error)
1728
+ };
1729
+ }
1730
+ }
784
1731
  /** Record a successful dial or transport-level operation. */
785
1732
  markOk(alias) {
786
1733
  this.health.set(alias, {
@@ -1184,9 +2131,39 @@ var RemotePool = class {
1184
2131
  * debug their network. Real transport failures still arrive through the
1185
2132
  * pooled connection's own close/error events.
1186
2133
  */
1187
- async forwardOut(alias, dstHost, dstPort, srcPort = 0) {
1188
- const conn = await this.acquire(alias);
1189
- this.hold(alias);
2134
+ async forwardOut(alias, dstHost, dstPort, srcPort = 0, opts = {}) {
2135
+ /**
2136
+ * Prefer the DEDICATED forward connection (see `forwardConns`). A host that
2137
+ * refuses the extra connection still forwards: the fallback is the shared
2138
+ * connection, i.e. exactly the old behaviour. The downgrade is logged once per
2139
+ * alias — a browser opens several forward channels per page, and one warning
2140
+ * per server refusal is information while one per channel is noise.
2141
+ *
2142
+ * Two short-circuits keep that preference from costing time:
2143
+ * - a recent refusal/timeout parks the alias for {@link FORWARD_DEDICATED_BLOCK_MS},
2144
+ * so the next channel goes straight to the shared connection;
2145
+ * - while a dedicated dial is already in flight, a second channel rides the
2146
+ * shared connection instead of waiting for the same handshake (it can only
2147
+ * be used by ONE `acquireIn` caller anyway).
2148
+ */
2149
+ let conn;
2150
+ let dedicated = opts.dedicated !== false;
2151
+ if (dedicated && this.forwardCoolingDown(alias)) dedicated = false;
2152
+ if (dedicated && this.forwardConns.get(alias)?.connecting !== void 0) dedicated = false;
2153
+ if (dedicated) try {
2154
+ conn = await this.acquireForward(alias);
2155
+ this.holdIn(this.forwardConns, alias);
2156
+ this.forwardBlocked.delete(alias);
2157
+ } catch (error) {
2158
+ dedicated = false;
2159
+ this.blockForward(alias, error);
2160
+ conn = await this.acquire(alias);
2161
+ this.hold(alias);
2162
+ }
2163
+ else {
2164
+ conn = await this.acquire(alias);
2165
+ this.hold(alias);
2166
+ }
1190
2167
  /**
1191
2168
  * What the channel-open callback does after the deadline already answered.
1192
2169
  *
@@ -1212,15 +2189,61 @@ var RemotePool = class {
1212
2189
  else resolve(stream);
1213
2190
  });
1214
2191
  }), 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;
2192
+ channel.once("close", () => {
2193
+ if (dedicated) this.releaseIn(this.forwardConns, alias);
2194
+ else this.release(alias);
2195
+ });
2196
+ if (!dedicated) this.markOk(alias);
2197
+ return {
2198
+ channel,
2199
+ dedicated
2200
+ };
1218
2201
  } catch (error) {
1219
2202
  settled = true;
1220
- this.release(alias);
2203
+ if (dedicated) this.releaseIn(this.forwardConns, alias);
2204
+ else this.release(alias);
2205
+ /**
2206
+ * NO `markError` here — deliberately.
2207
+ *
2208
+ * ssh2 reports EVERY direct-tcpip failure as
2209
+ * `(SSH) Channel open failure: <reason>`, and the pool's
2210
+ * `CONNECTION_ERROR_RE` matches `channel open fail`. A closed remote port or
2211
+ * `AllowTcpForwarding no` therefore LOOKS like a transport failure and used
2212
+ * to paint the connection chip red (sending the user to debug a healthy
2213
+ * network, and putting the editor into read-only). The function's contract
2214
+ * is the opposite: a channel-open refusal is the RULE's failure
2215
+ * (`forward.lastError`), while real transport failures surface through the
2216
+ * pooled connection's own close/error events.
2217
+ */
1221
2218
  throw error;
1222
2219
  }
1223
2220
  }
2221
+ /**
2222
+ * Is this alias's dedicated forward connection in its short cooldown?
2223
+ *
2224
+ * Expired entries are dropped eagerly so the map cannot grow per alias forever.
2225
+ */
2226
+ forwardCoolingDown(alias) {
2227
+ const until = this.forwardBlocked.get(alias);
2228
+ if (until === void 0) return false;
2229
+ if (Date.now() >= until) {
2230
+ this.forwardBlocked.delete(alias);
2231
+ return false;
2232
+ }
2233
+ return true;
2234
+ }
2235
+ /** Park the dedicated connection for one alias and log the downgrade, once. */
2236
+ blockForward(alias, error) {
2237
+ this.forwardBlocked.set(alias, Date.now() + FORWARD_DEDICATED_BLOCK_MS);
2238
+ this.noteForwardFallback(alias, error);
2239
+ }
2240
+ /** Log one alias's forward downgrade to the shared connection, once. */
2241
+ noteForwardFallback(alias, error) {
2242
+ if (this.forwardFallbackNoted.has(alias)) return;
2243
+ this.forwardFallbackNoted.add(alias);
2244
+ const detail = error instanceof Error ? error.message : String(error ?? "");
2245
+ console.warn(`[dsh-remote-vs] dedicated forward connection to ${alias} failed; using the shared one:`, detail);
2246
+ }
1224
2247
  /** Run one callback with a fresh SFTP session (closed afterwards). */
1225
2248
  async withSftp(alias, fn, opts = {}) {
1226
2249
  await this.acquireSlot(alias);
@@ -1714,7 +2737,32 @@ var RemotePool = class {
1714
2737
  async acquireShell(alias) {
1715
2738
  return this.acquireIn(this.shellConns, alias);
1716
2739
  }
1717
- async acquireIn(map, alias) {
2740
+ /**
2741
+ * `acquire` for the dedicated port-forward connection map.
2742
+ *
2743
+ * `quiet`: a dedicated forward connection is an OPTIMIZATION. If the server
2744
+ * refuses it (MaxStartups, `MaxSessions`, a per-source limit) the forward still
2745
+ * works over the shared connection, so the shared link is healthy — painting
2746
+ * the connection chip red here would send the user to debug a network that is
2747
+ * fine (and `forwardOut` reports the rule's own error separately).
2748
+ *
2749
+ * The dial also gets its OWN short budget ({@link FORWARD_DEDICATED_BUDGET_MS}):
2750
+ * a server that silently drops the extra connection would otherwise make every
2751
+ * forward channel wait the full connect watchdog before falling back. The
2752
+ * abandoned dial keeps running — if it eventually succeeds the connection is
2753
+ * pooled and the next channel uses it; its failure is already handled inside
2754
+ * `acquireIn`.
2755
+ */
2756
+ async acquireForward(alias) {
2757
+ const dialing = this.acquireIn(this.forwardConns, alias, true);
2758
+ try {
2759
+ return await withDeadline(dialing, FORWARD_DEDICATED_BUDGET_MS, `dedicated forward connection to ${alias} did not settle within ${FORWARD_DEDICATED_BUDGET_MS / 1e3}s`);
2760
+ } catch (error) {
2761
+ dialing.catch(() => void 0);
2762
+ throw error;
2763
+ }
2764
+ }
2765
+ async acquireIn(map, alias, quiet = false) {
1718
2766
  const pooled = map.get(alias);
1719
2767
  if (pooled !== void 0 && pooled.connecting !== void 0) return pooled.connecting;
1720
2768
  if (pooled !== void 0) {
@@ -1740,7 +2788,9 @@ var RemotePool = class {
1740
2788
  * so no idle timer arms, and `dispose()` only walks the map. Without the
1741
2789
  * failure check, a failed OLD dial deletes the NEW entry by alias.
1742
2790
  */
1743
- entry.connecting = this.dial(alias).then((conn) => {
2791
+ entry.connecting = this.dial(alias, (egress) => {
2792
+ if (map.get(alias) === entry) entry.egress = egress;
2793
+ }).then((conn) => {
1744
2794
  if (map.get(alias) !== entry) {
1745
2795
  try {
1746
2796
  conn.end();
@@ -1749,22 +2799,22 @@ var RemotePool = class {
1749
2799
  }
1750
2800
  entry.conn = conn;
1751
2801
  entry.connecting = void 0;
1752
- this.markOk(alias);
2802
+ if (!quiet) this.markOk(alias);
1753
2803
  conn.on("close", () => {
1754
2804
  if (map.get(alias) !== entry) return;
1755
- this.markError(alias, /* @__PURE__ */ new Error("connection closed"));
2805
+ if (!quiet) this.markError(alias, /* @__PURE__ */ new Error("connection closed"));
1756
2806
  this.evictFrom(map, alias);
1757
2807
  });
1758
2808
  conn.on("error", (error) => {
1759
2809
  if (map.get(alias) !== entry) return;
1760
- this.markError(alias, error);
2810
+ if (!quiet) this.markError(alias, error);
1761
2811
  this.evictFrom(map, alias);
1762
2812
  });
1763
2813
  this.releaseIn(map, alias);
1764
2814
  return conn;
1765
2815
  }, (error) => {
1766
2816
  if (map.get(alias) === entry) map.delete(alias);
1767
- this.markError(alias, error);
2817
+ if (!quiet) this.markError(alias, error);
1768
2818
  throw error;
1769
2819
  });
1770
2820
  return entry.connecting;
@@ -1775,6 +2825,7 @@ var RemotePool = class {
1775
2825
  if (pooled === void 0) return;
1776
2826
  map.delete(alias);
1777
2827
  if (pooled.timer !== void 0) clearTimeout(pooled.timer);
2828
+ pooled.egress = void 0;
1778
2829
  try {
1779
2830
  pooled.conn.end();
1780
2831
  } catch {}
@@ -1790,8 +2841,74 @@ var RemotePool = class {
1790
2841
  makeClient() {
1791
2842
  return new import_lib.Client();
1792
2843
  }
1793
- dial(alias) {
2844
+ /**
2845
+ * Open one SSH connection, through whatever route the store resolves.
2846
+ *
2847
+ * Three routes, and only the first is the pre-proxy code path:
2848
+ * - `direct`: unchanged (`host` / `port` in the connect config);
2849
+ * - `proxy`: the proxy module builds the tunnel and ssh2 rides the returned
2850
+ * socket (`sock`), so `host`/`port` are deliberately omitted (ssh2 ignores
2851
+ * them when `sock` is present);
2852
+ * - `jump`: the tunnel is a `direct-tcpip` channel on the JUMP host's pooled
2853
+ * connection, held for as long as the client lives. Its close/error handlers
2854
+ * close that channel and give the hold back — a leak here would pin the jump
2855
+ * host's connection forever.
2856
+ *
2857
+ * Every failure is a DIAL failure, so it keeps the existing `markError`
2858
+ * semantics; only the message is layered, so the user can tell which hop broke:
2859
+ * `proxy auth failed: …`, `proxy refused: …`, `jump host "x" failed: …`.
2860
+ *
2861
+ * `report` receives the route this dial ACTUALLY settled on, once and only on
2862
+ * success — a caller that asked "did this go through the jump host?" must not
2863
+ * be answered from a configuration that may have changed since. It is a
2864
+ * callback rather than a wider return type so the seam keeps returning the
2865
+ * `Client` the existing callers (and gates) hand around.
2866
+ */
2867
+ async dial(alias, report) {
1794
2868
  const host = this.store.require(alias);
2869
+ /** The socket ssh2 will ride, when a proxy/jump built one. */
2870
+ let sock;
2871
+ /** Runs once: tears the tunnel down (close the channel, release the jump). */
2872
+ let releaseTunnel;
2873
+ const route = this.store.resolveProxy(alias);
2874
+ const egress = egressOf(route, host);
2875
+ if (route.kind === "proxy") {
2876
+ try {
2877
+ sock = await openProxySocket(route.proxy, host.host, host.port);
2878
+ } catch (error) {
2879
+ throw proxyDialError(error, route.proxy);
2880
+ }
2881
+ releaseTunnel = () => {
2882
+ try {
2883
+ sock?.destroy();
2884
+ } catch {}
2885
+ };
2886
+ } else if (route.kind === "jump") {
2887
+ const via = route.viaAlias;
2888
+ try {
2889
+ await this.acquire(via);
2890
+ this.hold(via);
2891
+ } catch (error) {
2892
+ throw new Error(`jump host "${via}" failed: ${messageOf$3(error)}`);
2893
+ }
2894
+ let channel;
2895
+ try {
2896
+ channel = (await this.forwardOut(via, host.host, host.port, 0, { dedicated: false })).channel;
2897
+ } catch (error) {
2898
+ this.release(via);
2899
+ throw new Error(`jump host "${via}" failed: ${messageOf$3(error)}`);
2900
+ }
2901
+ let released = false;
2902
+ releaseTunnel = () => {
2903
+ if (released) return;
2904
+ released = true;
2905
+ try {
2906
+ channel.close();
2907
+ } catch {}
2908
+ this.release(via);
2909
+ };
2910
+ sock = channel;
2911
+ }
1795
2912
  return new Promise((resolve, reject) => {
1796
2913
  const conn = this.makeClient();
1797
2914
  let settled = false;
@@ -1803,12 +2920,14 @@ var RemotePool = class {
1803
2920
  try {
1804
2921
  conn.end();
1805
2922
  } catch {}
2923
+ releaseTunnel?.();
1806
2924
  reject(explainAuthError(host, error));
1807
2925
  };
1808
2926
  conn.on("ready", () => {
1809
2927
  if (settled) return;
1810
2928
  settled = true;
1811
2929
  if (guard !== void 0) clearTimeout(guard);
2930
+ report?.(egress);
1812
2931
  resolve(conn);
1813
2932
  });
1814
2933
  conn.on("error", (error) => fail(error));
@@ -1820,6 +2939,10 @@ var RemotePool = class {
1820
2939
  * leave this promise pending forever while the caller held a channel slot.
1821
2940
  */
1822
2941
  conn.on("close", () => fail(/* @__PURE__ */ new Error("connection closed during SSH handshake")));
2942
+ if (releaseTunnel !== void 0) {
2943
+ conn.once("close", () => releaseTunnel?.());
2944
+ conn.once("error", () => releaseTunnel?.());
2945
+ }
1823
2946
  guard = setTimeout(() => {
1824
2947
  fail(/* @__PURE__ */ new Error(`SSH handshake did not settle within ${(READY_TIMEOUT_MS + DIAL_GUARD_MARGIN_MS) / 1e3}s`));
1825
2948
  }, READY_TIMEOUT_MS + DIAL_GUARD_MARGIN_MS);
@@ -1845,11 +2968,14 @@ var RemotePool = class {
1845
2968
  return true;
1846
2969
  };
1847
2970
  try {
2971
+ const transport = sock === void 0 ? {
2972
+ host: host.host,
2973
+ port: host.port
2974
+ } : { sock };
1848
2975
  if (host.auth.kind === "key") {
1849
2976
  const keyPath = host.auth.keyPath;
1850
2977
  conn.connect({
1851
- host: host.host,
1852
- port: host.port,
2978
+ ...transport,
1853
2979
  username: host.user,
1854
2980
  privateKey: readFileSync(keyPath),
1855
2981
  passphrase: host.auth.passphrase,
@@ -1859,8 +2985,7 @@ var RemotePool = class {
1859
2985
  hostVerifier
1860
2986
  });
1861
2987
  } else conn.connect({
1862
- host: host.host,
1863
- port: host.port,
2988
+ ...transport,
1864
2989
  username: host.user,
1865
2990
  password: host.auth.password,
1866
2991
  tryKeyboard: true,
@@ -1876,6 +3001,83 @@ var RemotePool = class {
1876
3001
  }
1877
3002
  };
1878
3003
  /**
3004
+ * The route one resolved proxy decision describes, in the shape the chip prints.
3005
+ *
3006
+ * `detail` is the HOP, never a sentence: the target `host:port` for a direct
3007
+ * connection, the proxy `host:port` for a tunnel, the jump host's alias for a
3008
+ * chain. The wording belongs to the localized client — a second English sentence
3009
+ * baked in here would leak into the Chinese tooltip.
3010
+ */
3011
+ function egressOf(route, host) {
3012
+ if (route.kind === "proxy") return {
3013
+ kind: "proxy",
3014
+ detail: `${route.proxy.host}:${route.proxy.port}`,
3015
+ source: route.source,
3016
+ proxyKind: route.proxy.kind
3017
+ };
3018
+ if (route.kind === "jump") return {
3019
+ kind: "jump",
3020
+ detail: route.viaAlias,
3021
+ viaAlias: route.viaAlias
3022
+ };
3023
+ return {
3024
+ kind: "direct",
3025
+ detail: `${host.host}:${host.port}`
3026
+ };
3027
+ }
3028
+ /**
3029
+ * Best-effort route from the STORED fields, for the one case `resolveProxy`
3030
+ * refuses to answer (a dangling jump chain, a self-jump, a proxy setting that
3031
+ * does not validate). The caller adds `problem` with the reason; the shape here
3032
+ * only says WHICH kind of route is broken, so the chip can name it.
3033
+ */
3034
+ function storedEgress(host) {
3035
+ const jump = host.proxy?.jump?.viaAlias;
3036
+ if (host.proxy?.mode === "jump") return {
3037
+ kind: "jump",
3038
+ detail: jump ?? "",
3039
+ ...jump === void 0 ? {} : { viaAlias: jump }
3040
+ };
3041
+ const proxy = host.proxy?.proxy;
3042
+ if (proxy !== void 0) return {
3043
+ kind: "proxy",
3044
+ detail: `${proxy.host}:${proxy.port}`,
3045
+ proxyKind: proxy.kind
3046
+ };
3047
+ return {
3048
+ kind: "direct",
3049
+ detail: `${host.host}:${host.port}`
3050
+ };
3051
+ }
3052
+ /** Message of an unknown thrown value, without assuming it is an `Error`. */
3053
+ function messageOf$3(error) {
3054
+ return error instanceof Error ? error.message : String(error ?? "");
3055
+ }
3056
+ /**
3057
+ * Fixed prefix per proxy failure reason.
3058
+ *
3059
+ * The dial fails either way; the prefix is what tells the user WHICH layer broke —
3060
+ * their password, the proxy host, the tunnel policy, or the destination. The raw
3061
+ * detail is kept after it, so nothing is lost.
3062
+ */
3063
+ const PROXY_FAILURE_PREFIX = {
3064
+ unreachable: "proxy unreachable",
3065
+ timeout: "proxy timed out",
3066
+ auth: "proxy auth failed",
3067
+ refused: "proxy refused",
3068
+ protocol: "proxy protocol error",
3069
+ target: "proxy target invalid"
3070
+ };
3071
+ /** One proxy dial failure, with the layer in front of the original message. */
3072
+ function proxyDialError(error, proxy) {
3073
+ if (error instanceof ProxyError) {
3074
+ const prefix = PROXY_FAILURE_PREFIX[error.reason];
3075
+ const where = error.reason === "target" ? "" : ` ${proxy.kind} proxy ${proxy.host}:${proxy.port}`;
3076
+ return /* @__PURE__ */ new Error(`${prefix}${where}: ${error.message}`);
3077
+ }
3078
+ return /* @__PURE__ */ new Error(`proxy failed: ${proxy.kind} proxy ${proxy.host}:${proxy.port}: ${messageOf$3(error)}`);
3079
+ }
3080
+ /**
1879
3081
  * Translate ssh2's generic auth failure into something actionable. Never
1880
3082
  * includes secrets — only the entry shape and the likely server-side causes.
1881
3083
  */
@@ -2182,6 +3384,7 @@ var ForwardManager = class {
2182
3384
  bytesIn: 0,
2183
3385
  bytesOut: 0,
2184
3386
  lastError: void 0,
3387
+ transport: void 0,
2185
3388
  startedAt: Date.now()
2186
3389
  };
2187
3390
  server.on("connection", (socket) => {
@@ -2246,7 +3449,16 @@ var ForwardManager = class {
2246
3449
  async connect(forward, socket) {
2247
3450
  let channel;
2248
3451
  try {
2249
- channel = await this.deps.pool.forwardOut(forward.alias, forward.remoteHost, forward.remotePort);
3452
+ /**
3453
+ * Ask for the host's DEDICATED forward connection: forwarding traffic is
3454
+ * long-lived and heavy, and multiplexed onto the shared connection it would
3455
+ * queue ahead of exec/SFTP channels. The pool falls back on its own when the
3456
+ * server refuses the extra connection, and tells us which one was used so
3457
+ * the row can say so.
3458
+ */
3459
+ const opened = await this.deps.pool.forwardOut(forward.alias, forward.remoteHost, forward.remotePort, 0, { dedicated: true });
3460
+ channel = opened.channel;
3461
+ forward.transport = opened.dedicated ? "dedicated" : "shared";
2250
3462
  } catch (error) {
2251
3463
  forward.lastError = messageOf$2(error);
2252
3464
  this.log("warn", `forward ${forward.id} -> ${forward.remoteHost}:${forward.remotePort} failed: ${forward.lastError}`);
@@ -2313,6 +3525,7 @@ var ForwardManager = class {
2313
3525
  bytesIn: forward.bytesIn,
2314
3526
  bytesOut: forward.bytesOut,
2315
3527
  ...forward.lastError === void 0 ? {} : { lastError: forward.lastError },
3528
+ ...forward.transport === void 0 ? {} : { transport: forward.transport },
2316
3529
  startedAt: forward.startedAt
2317
3530
  };
2318
3531
  }
@@ -2666,7 +3879,7 @@ async function bootstrap(pool, store, alias) {
2666
3879
  kind: "key",
2667
3880
  keyPath: privatePath
2668
3881
  } });
2669
- pool.drop(alias);
3882
+ pool.forget(alias);
2670
3883
  const check = await pool.test(alias);
2671
3884
  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
3885
  return {
@@ -2681,8 +3894,12 @@ async function bootstrap(pool, store, alias) {
2681
3894
  /**
2682
3895
  * One-shot importers: ~/.ssh/config and the existing dsh-ssh.json. Both only
2683
3896
  * 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.
3897
+ * Hosts are direct key hosts; the egress half of a `Host` block (`ProxyJump` /
3898
+ * `ProxyCommand`) is mapped onto the store's `proxy` field when it names
3899
+ * something this import actually produces, and refused BY NAME when it names a
3900
+ * form this plugin cannot dial (multi-hop, a shell command, a jump host that is
3901
+ * not part of the config). A silent skip used to be the answer to all of them;
3902
+ * "one hop, from this same config" is the honest boundary.
2686
3903
  */
2687
3904
  /** Expand a leading ~ to the user home. */
2688
3905
  function expandHome(path) {
@@ -2702,9 +3919,89 @@ function validPort(value) {
2702
3919
  if (!Number.isInteger(port) || port < 1 || port > 65535) return void 0;
2703
3920
  return port;
2704
3921
  }
3922
+ /** `ProxyJump none` / `ProxyCommand none` is OpenSSH for "explicitly no proxy". */
3923
+ function isNone(value) {
3924
+ return value.trim().toLowerCase() === "none";
3925
+ }
3926
+ /**
3927
+ * Index every name an imported host answers to: its alias and its `HostName`.
3928
+ *
3929
+ * `ProxyJump bastion` may name the `Host bastion` alias or the literal hostname
3930
+ * it resolves to, so both are accepted; a name with no host behind it in THIS
3931
+ * config cannot become a `viaAlias` (the stored setting would dangle).
3932
+ */
3933
+ function nameIndex(candidates) {
3934
+ const index = /* @__PURE__ */ new Map();
3935
+ for (const candidate of candidates) {
3936
+ index.set(candidate.alias, candidate.alias);
3937
+ index.set(candidate.alias.toLowerCase(), candidate.alias);
3938
+ index.set(candidate.hostname, candidate.alias);
3939
+ index.set(candidate.hostname.toLowerCase(), candidate.alias);
3940
+ }
3941
+ return index;
3942
+ }
3943
+ /** Resolve one jump host name against the hosts this import creates. */
3944
+ function resolveJump(self, name, index) {
3945
+ const viaAlias = index.get(name) ?? index.get(name.toLowerCase());
3946
+ if (viaAlias === void 0) return {
3947
+ ok: false,
3948
+ reason: `jump host '${name}' is not imported by this config — a jump host must be one of its Host entries`
3949
+ };
3950
+ if (viaAlias === self) return {
3951
+ ok: false,
3952
+ reason: `jump host '${name}' is this host itself`
3953
+ };
3954
+ return {
3955
+ ok: true,
3956
+ proxy: {
3957
+ mode: "jump",
3958
+ jump: { viaAlias }
3959
+ }
3960
+ };
3961
+ }
3962
+ /**
3963
+ * Turn one block's egress directive into the store's proxy decision.
3964
+ *
3965
+ * Precedence matches OpenSSH (a set `ProxyJump` wins over `ProxyCommand`), and
3966
+ * everything unusable keeps the PARSER's own reason so the report says what to
3967
+ * fix ("only one hop", "not supported program") instead of a generic skip.
3968
+ */
3969
+ function resolveProxy(self, fields, index) {
3970
+ const jump = fields.get("proxyjump");
3971
+ if (jump !== void 0) {
3972
+ if (isNone(jump)) return { ok: true };
3973
+ const parsed = parseProxyJump(jump);
3974
+ if (!parsed.ok) return {
3975
+ ok: false,
3976
+ reason: parsed.reason
3977
+ };
3978
+ return resolveJump(self, parsed.target.host, index);
3979
+ }
3980
+ const command = fields.get("proxycommand");
3981
+ if (command !== void 0) {
3982
+ if (isNone(command)) return { ok: true };
3983
+ const plan = parseProxyCommand(command);
3984
+ if (plan.kind === "proxy") return {
3985
+ ok: true,
3986
+ proxy: {
3987
+ mode: "proxy",
3988
+ proxy: {
3989
+ kind: plan.proxy.kind,
3990
+ host: plan.proxy.host,
3991
+ port: plan.proxy.port
3992
+ }
3993
+ }
3994
+ };
3995
+ if (plan.kind === "jump") return resolveJump(self, plan.target.host, index);
3996
+ return {
3997
+ ok: false,
3998
+ reason: plan.reason
3999
+ };
4000
+ }
4001
+ return { ok: true };
4002
+ }
2705
4003
  /** Parse OpenSSH client config text into host payloads. */
2706
4004
  function parseSshConfig(text) {
2707
- const payloads = [];
2708
4005
  const skipped = [];
2709
4006
  const blocks = [];
2710
4007
  let current;
@@ -2735,6 +4032,7 @@ function parseSshConfig(text) {
2735
4032
  });
2736
4033
  else if (current !== void 0 && !current.fields.has(key)) current.fields.set(key, value);
2737
4034
  }
4035
+ const candidates = [];
2738
4036
  for (const block of blocks) {
2739
4037
  const concrete = block.patterns.filter((pattern) => pattern !== "" && !/[*?!]/.test(pattern));
2740
4038
  const special = block.patterns.filter((pattern) => pattern !== "" && /[*?!]/.test(pattern));
@@ -2749,13 +4047,6 @@ function parseSshConfig(text) {
2749
4047
  });
2750
4048
  continue;
2751
4049
  }
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
4050
  const rawPort = block.fields.get("port");
2760
4051
  const port = rawPort === void 0 ? 22 : validPort(rawPort);
2761
4052
  const identityFile = block.fields.get("identityfile")?.split(/\s+/)[0];
@@ -2782,18 +4073,39 @@ function parseSshConfig(text) {
2782
4073
  });
2783
4074
  continue;
2784
4075
  }
2785
- payloads.push({
4076
+ candidates.push({
2786
4077
  alias,
2787
- host: block.fields.get("hostname") ?? alias,
4078
+ hostname: block.fields.get("hostname") ?? alias,
2788
4079
  port,
2789
4080
  user,
2790
- auth: {
2791
- kind: "key",
2792
- keyPath: expandHome(identityFile)
2793
- },
2794
- tags: ["imported:ssh-config"]
4081
+ identityFile,
4082
+ fields: block.fields
4083
+ });
4084
+ }
4085
+ }
4086
+ const index = nameIndex(candidates);
4087
+ const payloads = [];
4088
+ for (const candidate of candidates) {
4089
+ const resolution = resolveProxy(candidate.alias, candidate.fields, index);
4090
+ if (!resolution.ok) {
4091
+ skipped.push({
4092
+ alias: candidate.alias,
4093
+ reason: resolution.reason
2795
4094
  });
4095
+ continue;
2796
4096
  }
4097
+ payloads.push({
4098
+ alias: candidate.alias,
4099
+ host: candidate.hostname,
4100
+ port: candidate.port,
4101
+ user: candidate.user,
4102
+ auth: {
4103
+ kind: "key",
4104
+ keyPath: expandHome(candidate.identityFile)
4105
+ },
4106
+ tags: ["imported:ssh-config"],
4107
+ ...resolution.proxy === void 0 ? {} : { proxy: resolution.proxy }
4108
+ });
2797
4109
  }
2798
4110
  return {
2799
4111
  payloads,
@@ -2831,7 +4143,7 @@ function migrateDshSsh(home = dshHome()) {
2831
4143
  if (hasProxy) {
2832
4144
  skipped.push({
2833
4145
  alias,
2834
- reason: "proxyJump/proxyCommand needs P1 (direct hosts only in P0)"
4146
+ reason: "proxyJump/proxyCommand in dsh-ssh.json is not mapped — import from ~/.ssh/config instead"
2835
4147
  });
2836
4148
  continue;
2837
4149
  }
@@ -4321,17 +5633,30 @@ function makeRoutes(deps) {
4321
5633
  });
4322
5634
  res.on("close", () => stop());
4323
5635
  };
4324
- /** Apply parsed import payloads; per-entry errors become skips. */
5636
+ /**
5637
+ * Apply parsed import payloads; per-entry errors become skips.
5638
+ *
5639
+ * Two rounds, jump rows LAST, because a `jump` decision names ANOTHER host and
5640
+ * `store.create` refuses a `viaAlias` that is not stored yet. Payload order is
5641
+ * the order of the source file, which is not a dependency order: a config that
5642
+ * writes `Host target` (`ProxyJump bastion`) before `Host bastion` used to
5643
+ * import the bastion and silently drop the host that needs it, reported only as
5644
+ * `proxy.jump.viaAlias: unknown host alias bastion`. One hop is the supported
5645
+ * shape (a jump host is never itself a jump host), so two rounds always
5646
+ * suffice; whatever is still unknown in round two is a host this import did
5647
+ * not create (it was skipped for its own reason, which the report already
5648
+ * carries), and stays a skip with the store's own wording.
5649
+ */
4325
5650
  const applyImport = (parsed) => {
4326
5651
  const imported = [];
4327
5652
  const skipped = [...parsed.skipped];
4328
- for (const payload of parsed.payloads) {
5653
+ const create = (payload) => {
4329
5654
  if (store.get(payload.alias) !== void 0) {
4330
5655
  skipped.push({
4331
5656
  alias: payload.alias,
4332
5657
  reason: "alias already exists"
4333
5658
  });
4334
- continue;
5659
+ return;
4335
5660
  }
4336
5661
  try {
4337
5662
  store.create(payload);
@@ -4342,7 +5667,9 @@ function makeRoutes(deps) {
4342
5667
  reason: error instanceof Error ? error.message : String(error)
4343
5668
  });
4344
5669
  }
4345
- }
5670
+ };
5671
+ for (const payload of parsed.payloads.filter((entry) => entry.proxy?.mode !== "jump")) create(payload);
5672
+ for (const payload of parsed.payloads.filter((entry) => entry.proxy?.mode === "jump")) create(payload);
4346
5673
  return {
4347
5674
  imported,
4348
5675
  skipped
@@ -4414,11 +5741,11 @@ function makeRoutes(deps) {
4414
5741
  return;
4415
5742
  }
4416
5743
  try {
5744
+ const entry = store.update(alias, body);
4417
5745
  pool.forget(alias);
4418
5746
  monitor.forget(alias);
4419
5747
  forgetProcesses(alias);
4420
5748
  worlds.dropHost(alias).catch(() => void 0);
4421
- const entry = store.update(alias, body);
4422
5749
  writeJson(res, 200, { host: store.summarize(entry) });
4423
5750
  } catch (error) {
4424
5751
  writeJson(res, (error instanceof Error ? error.message : "").startsWith("unknown host alias") ? 404 : 400, { error: error instanceof Error ? error.message : String(error) });
@@ -5049,8 +6376,8 @@ function makeRoutes(deps) {
5049
6376
  const body = read.body;
5050
6377
  const sessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
5051
6378
  const op = typeof body?.op === "string" ? body.op : "";
5052
- if (sessionId === "" || op !== "list" && op !== "diff") {
5053
- writeJson(res, 400, { error: "op (list|diff) and a non-empty sessionId are required" });
6379
+ if (sessionId === "" || op !== "list" && op !== "diff" && op !== "turnDiff") {
6380
+ writeJson(res, 400, { error: "op (list|diff|turnDiff) and a non-empty sessionId are required" });
5054
6381
  return;
5055
6382
  }
5056
6383
  const ledger = deps.changes;
@@ -5071,17 +6398,18 @@ function makeRoutes(deps) {
5071
6398
  });
5072
6399
  }
5073
6400
  if (body?.force === true) ledger.rescan(sessionId);
6401
+ else if (body?.trackedOnly === true) ledger.touch(sessionId, 0);
5074
6402
  else ledger.touch(sessionId);
5075
6403
  writeJson(res, 200, { summary: ledger.summary(sessionId) });
5076
6404
  return;
5077
6405
  }
5078
6406
  const path = typeof body?.path === "string" ? body.path : "";
5079
6407
  if (path === "") {
5080
- writeJson(res, 400, { error: "path is required for op=diff" });
6408
+ writeJson(res, 400, { error: `path is required for op=${op}` });
5081
6409
  return;
5082
6410
  }
5083
6411
  try {
5084
- writeJson(res, 200, { diff: await ledger.diff(sessionId, path) });
6412
+ writeJson(res, 200, { diff: op === "turnDiff" ? await ledger.turnDiff(sessionId, path) : await ledger.diff(sessionId, path) });
5085
6413
  } catch (error) {
5086
6414
  writeRouteError(res, error);
5087
6415
  }
@@ -5150,6 +6478,40 @@ function makeRoutes(deps) {
5150
6478
  }
5151
6479
  }
5152
6480
  },
6481
+ {
6482
+ kind: "exact",
6483
+ path: REMOTE_API.proxySettings,
6484
+ handler: async (req, res) => {
6485
+ if (!isLoopbackRequest(req)) {
6486
+ writeJson(res, 403, { error: "forbidden: loopback-only" });
6487
+ return;
6488
+ }
6489
+ const method = req.method ?? "GET";
6490
+ if (method === "GET") {
6491
+ try {
6492
+ writeJson(res, 200, { settings: store.getDefaultProxy() });
6493
+ } catch (error) {
6494
+ writeStoreError(res, error);
6495
+ }
6496
+ return;
6497
+ }
6498
+ if (method !== "POST" && method !== "PATCH") {
6499
+ writeJson(res, 405, { error: `method not allowed: ${method}` });
6500
+ return;
6501
+ }
6502
+ const read = await readBodyOrError(req, res, { objectOnly: true });
6503
+ if (!read.ok) return;
6504
+ try {
6505
+ writeJson(res, 200, { settings: store.patchDefaultProxy(read.body ?? {}) });
6506
+ } catch (error) {
6507
+ if (isStoreError(error)) {
6508
+ writeStoreError(res, error);
6509
+ return;
6510
+ }
6511
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
6512
+ }
6513
+ }
6514
+ },
5153
6515
  {
5154
6516
  kind: "exact",
5155
6517
  path: REMOTE_API.deploy,
@@ -6509,6 +7871,17 @@ function filePatch(displayPath, hunks) {
6509
7871
  function panelStatus(status) {
6510
7872
  return status === "?" ? "A" : status;
6511
7873
  }
7874
+ /** Text of one read result, with "nothing usable transferred" folded into null. */
7875
+ function turnSideOf(read) {
7876
+ const binary = read.binary === true;
7877
+ const truncated = read.truncated === true;
7878
+ return {
7879
+ text: read.absent || binary || truncated ? null : read.text,
7880
+ binary,
7881
+ truncated,
7882
+ known: !binary && !truncated
7883
+ };
7884
+ }
6512
7885
  /** Grace added to an exec budget before the watchdog gives up on it. */
6513
7886
  const WATCHDOG_GRACE_MS = 5e3;
6514
7887
  /** Sentinel for "the host call never came back". */
@@ -6527,6 +7900,66 @@ const DIFF_LIMITS = {
6527
7900
  perFile: DIFF_MAX_FILE_BYTES,
6528
7901
  total: DIFF_MAX_FILE_BYTES
6529
7902
  };
7903
+ /**
7904
+ * Budget for ONE completed turn's **per-file hunks and reverse patches**.
7905
+ *
7906
+ * What it counts (and what it deliberately does NOT): the sum of every served
7907
+ * file patch plus the hunk line bodies. The two FULL texts per record (`before`
7908
+ * and `after`) and the `turnAfter` snapshot are not counted — they are what the
7909
+ * staleness proof compares against, and they are already bounded by the scan
7910
+ * caps (≲256 KiB/file, 8 MiB/turn for `after` plus the same order for `before`
7911
+ * and the snapshot). So the real resident cost is this budget PLUS those texts
7912
+ * (worst case ≈ 16 MiB + 4 MiB per active session), which is why the copy says
7913
+ * "patches and hunk text" rather than "the turn's contents".
7914
+ *
7915
+ * The turn view must keep a comparison per changed file until the next turn
7916
+ * closes (that is what `turnDiff` serves without re-reading the remote). 4 MiB
7917
+ * fits a large refactor's patches; crossing it disables per-turn hunks for the
7918
+ * session (see {@link Ledger.turnDisabled}) rather than thrashing the budget.
7919
+ */
7920
+ const MAX_TURN_PATCH_BYTES = 4 * 1024 * 1024;
7921
+ /**
7922
+ * Bounds of the self-heal window (see {@link selfHealMaxAge}).
7923
+ *
7924
+ * The floor is a measured small repository: `git status -uno` answers in ~0.1s
7925
+ * there, so 5s of staleness is already a large win over the old flat 30s — and
7926
+ * the probe has been observed to take 30–60s to surface a manual edit when only
7927
+ * the turn boundary and the 3/15/30s client polls apply.
7928
+ *
7929
+ * The ceiling is the OLD fixed value on purpose: it is what keeps the panel from
7930
+ * turning into a status loop on a huge checkout (the reference monorepo answers
7931
+ * in ~1.7s, i.e. a 6.8s window — still 4x its own cost, never lower for bigger
7932
+ * trees).
7933
+ */
7934
+ const SELF_HEAL_MIN_MS = 5e3;
7935
+ const SELF_HEAL_MAX_MS = 3e4;
7936
+ /**
7937
+ * How many scan durations the panel may wait before re-scanning.
7938
+ *
7939
+ * Self-heal is a POLL backstop, not a live watch: waiting the cost of about four
7940
+ * `git status -uno` runs keeps the added load proportional to what the probe can
7941
+ * afford, instead of one scan per client poll.
7942
+ */
7943
+ const SELF_HEAL_FACTOR = 4;
7944
+ /**
7945
+ * How stale the ledger may get before a *poll* re-scans it.
7946
+ *
7947
+ * Self-tuning: the host has no idea whether this session sits in a 50-file
7948
+ * repository or a monorepo, and the same 30s window is either 300x the scan cost
7949
+ * (small tree: the user waits half a minute to see a manual edit) or about right
7950
+ * (AOSP: still 17x). Four times the LAST tracked scan, clamped to
7951
+ * [{@link SELF_HEAL_MIN_MS}, {@link SELF_HEAL_MAX_MS}].
7952
+ *
7953
+ * An unknown / failed measurement falls back to the old ceiling, so a Host that
7954
+ * has not scanned anything yet behaves exactly as before.
7955
+ *
7956
+ * @param scanMs - Duration of the last successful tracked scan, in ms.
7957
+ */
7958
+ function selfHealMaxAge(scanMs) {
7959
+ if (scanMs === void 0 || !Number.isFinite(scanMs) || scanMs < 0) return SELF_HEAL_MAX_MS;
7960
+ const scaled = Math.round(scanMs * SELF_HEAL_FACTOR);
7961
+ return Math.min(SELF_HEAL_MAX_MS, Math.max(SELF_HEAL_MIN_MS, scaled));
7962
+ }
6530
7963
  /** POSIX join — `node:path` would apply Windows semantics on the host. */
6531
7964
  function posixJoin(base, rel) {
6532
7965
  if (rel.startsWith("/")) return rel;
@@ -6534,6 +7967,11 @@ function posixJoin(base, rel) {
6534
7967
  const right = rel.startsWith("./") ? rel.slice(2) : rel;
6535
7968
  return right === "" ? left : `${left}/${right}`;
6536
7969
  }
7970
+ /** The inverse of {@link posixJoin} for a path under `root`; '' when it is not. */
7971
+ function displayUnder(root, path) {
7972
+ const base = root.endsWith("/") ? root : `${root}/`;
7973
+ return path.startsWith(base) ? path.slice(base.length) : "";
7974
+ }
6537
7975
  /**
6538
7976
  * Whether two reads prove the file did not move between them.
6539
7977
  *
@@ -6568,7 +8006,9 @@ var SessionChanges = class {
6568
8006
  if (this.disposed) return;
6569
8007
  const ledger = this.ensure(target);
6570
8008
  if (ledger === void 0) return;
8009
+ const advanced = turn > ledger.turn;
6571
8010
  ledger.turn = Math.max(ledger.turn, turn);
8011
+ if (advanced) ledger.pendingClose = turn;
6572
8012
  this.schedule(ledger);
6573
8013
  }
6574
8014
  /** The current summary for one session, or null when it has no ledger. */
@@ -6588,7 +8028,18 @@ var SessionChanges = class {
6588
8028
  ...excludedDirs.length === 0 ? {} : { excludedDirs },
6589
8029
  pending: ledger.untrackedJob !== void 0 || ledger.pending && ledger.files.length > 0,
6590
8030
  ...ledger.truncated === true ? { truncated: true } : {},
6591
- ...unavailable === void 0 ? {} : { unavailable }
8031
+ ...unavailable === void 0 ? {} : { unavailable },
8032
+ ...ledger.turnDelta === void 0 ? {} : { turnView: {
8033
+ turn: ledger.turnDelta.turn,
8034
+ files: ledger.turnDelta.files,
8035
+ added: ledger.turnDelta.added,
8036
+ deleted: ledger.turnDelta.deleted,
8037
+ at: ledger.turnDelta.at,
8038
+ cached: ledger.turnDelta.cached,
8039
+ ...ledger.turnDelta.reason === void 0 ? {} : { reason: ledger.turnDelta.reason },
8040
+ ...ledger.turnDelta.truncated === true ? { truncated: true } : {},
8041
+ ...ledger.turnDelta.provisional ? { pending: true } : {}
8042
+ } }
6592
8043
  };
6593
8044
  }
6594
8045
  /**
@@ -6662,21 +8113,158 @@ var SessionChanges = class {
6662
8113
  lines: hunk.lines,
6663
8114
  patch: reverse === "" ? "" : hunkPatch(record.display, hunk)
6664
8115
  }));
6665
- if (hunks.length === 0) return {
6666
- kind: "missing",
8116
+ if (hunks.length === 0) {
8117
+ /**
8118
+ * Both sides were READ and compared, so "no hunks" means the file is back
8119
+ * at its session baseline (the change was reverted, or an identical byte
8120
+ * round-trip). That is NOT "missing": the panel shows `missing` as "the
8121
+ * remote cannot read this file", and saying that about a file the host
8122
+ * just read is a lie that also hides "your change is gone". A withheld
8123
+ * side (null) keeps `missing` — there is genuinely nothing to compare.
8124
+ */
8125
+ /**
8126
+ * 判定只看**改后那一侧读到了**:新建的空文件 before 是 null(不存在),after
8127
+ * 读到 `''`,零 hunk 是"读到了、只是没有内容",不是"读不到"。老条件要求两侧
8128
+ * 都非 null,于是会话新建的空文件被报成 `missing`,面板显示「远端读不到」
8129
+ * (审核 NIT-1)。
8130
+ */
8131
+ if (afterText !== null) return {
8132
+ kind: "text",
8133
+ path,
8134
+ display: record.display,
8135
+ hunks: [],
8136
+ ...status === void 0 ? {} : { status }
8137
+ };
8138
+ return {
8139
+ kind: "missing",
8140
+ path,
8141
+ display: record.display,
8142
+ hunks: [],
8143
+ ...status === void 0 ? {} : { status }
8144
+ };
8145
+ }
8146
+ return {
8147
+ kind: "text",
8148
+ path,
8149
+ display: record.display,
8150
+ hunks,
8151
+ ...reverse === "" ? {} : { patch: reverse },
8152
+ ...status === void 0 ? {} : { status },
8153
+ ...truncated ? { truncated: true } : {}
8154
+ };
8155
+ }
8156
+ /**
8157
+ * One file's comparison for the most recent COMPLETED turn.
8158
+ *
8159
+ * Same shape as {@link diff} (the editor paints both the same way), but the
8160
+ * "before" side is the previous turn's close instead of the session baseline.
8161
+ * The hunks are served from the turn delta's cache, so this call costs NO
8162
+ * remote work in the common case — but a cached comparison is only worth
8163
+ * showing while it still describes the disk. That is why the `after` side is
8164
+ * read back here and compared with the cached text FIRST: if the file moved on
8165
+ * after the turn closed (a later save, a terminal command, an agent), the
8166
+ * answer is `stale` and the client falls back to the session view instead of
8167
+ * painting line numbers that no longer exist.
8168
+ *
8169
+ * @param sessionId - live session owning the ledger.
8170
+ * @param path - the file's remote absolute path (as listed in `turnView.files`).
8171
+ * @returns hunks for decorations, `unavailable`/`stale` with a reason, or null
8172
+ * when the session itself is unknown.
8173
+ */
8174
+ async turnDiff(sessionId, path) {
8175
+ const ledger = this.ledgers.get(sessionId);
8176
+ if (ledger === void 0) return null;
8177
+ const delta = ledger.turnDelta;
8178
+ const display = delta?.records.get(path)?.display ?? displayUnder(ledger.root, path);
8179
+ if (delta === void 0) return {
8180
+ kind: "unavailable",
8181
+ path,
8182
+ display,
8183
+ hunks: [],
8184
+ reason: "no turn has closed since this session started"
8185
+ };
8186
+ if (!delta.cached) return {
8187
+ kind: "unavailable",
8188
+ path,
8189
+ display,
8190
+ hunks: [],
8191
+ reason: delta.reason ?? "per-turn change contents are not cached for this session"
8192
+ };
8193
+ const record = delta.records.get(path);
8194
+ if (record === void 0) return {
8195
+ kind: "unavailable",
8196
+ path,
8197
+ display,
8198
+ hunks: [],
8199
+ reason: `this file is not part of turn ${delta.turn}'s change set`
8200
+ };
8201
+ const status = record.status;
8202
+ if (record.binary) return {
8203
+ kind: "binary",
8204
+ path,
8205
+ display: record.display,
8206
+ hunks: [],
8207
+ ...status === void 0 ? {} : { status }
8208
+ };
8209
+ if (record.oversized) return {
8210
+ kind: "unavailable",
8211
+ path,
8212
+ display: record.display,
8213
+ hunks: [],
8214
+ reason: "the bytes of this file were withheld by the size cap, so there is no line-level comparison",
8215
+ ...status === void 0 ? {} : { status }
8216
+ };
8217
+ /**
8218
+ * Verify the cache against the disk before serving it.
8219
+ *
8220
+ * A failed read is NOT "unchanged": without evidence the honest answer is
8221
+ * `unavailable` (no palatable guess). A binary or cap-truncated read proves
8222
+ * the bytes moved on after the turn closed, which is exactly `stale`.
8223
+ */
8224
+ const fresh = await this.readPaths(ledger, [record.display], "worktree", DIFF_LIMITS);
8225
+ if (ledger.disposed) return null;
8226
+ const side = fresh.get(record.display);
8227
+ if (side === void 0) return {
8228
+ kind: "unavailable",
6667
8229
  path,
6668
8230
  display: record.display,
6669
8231
  hunks: [],
8232
+ reason: "the file could not be read back from the host, so the turn comparison cannot be verified",
6670
8233
  ...status === void 0 ? {} : { status }
6671
8234
  };
8235
+ const current = turnSideOf(side);
8236
+ if (current.binary || current.truncated) return {
8237
+ kind: "stale",
8238
+ path,
8239
+ display: record.display,
8240
+ hunks: [],
8241
+ reason: current.binary ? "the file has become binary since the turn closed" : "the file has grown past the read budget since the turn closed",
8242
+ ...status === void 0 ? {} : { status }
8243
+ };
8244
+ if (current.text !== record.after) return {
8245
+ kind: "stale",
8246
+ path,
8247
+ display: record.display,
8248
+ hunks: [],
8249
+ reason: "the file was modified after the turn closed",
8250
+ ...status === void 0 ? {} : { status }
8251
+ };
8252
+ const hunks = record.hunks.map((hunk) => ({
8253
+ oldStart: hunk.oldStart,
8254
+ oldCount: hunk.oldLines,
8255
+ newStart: hunk.newStart,
8256
+ newCount: hunk.newLines,
8257
+ heading: "",
8258
+ lines: hunk.lines,
8259
+ patch: record.filePatch === "" ? "" : hunkPatch(record.display, hunk)
8260
+ }));
6672
8261
  return {
6673
8262
  kind: "text",
6674
8263
  path,
6675
8264
  display: record.display,
6676
8265
  hunks,
6677
- ...reverse === "" ? {} : { patch: reverse },
6678
- ...status === void 0 ? {} : { status },
6679
- ...truncated ? { truncated: true } : {}
8266
+ ...record.filePatch === "" ? {} : { patch: record.filePatch },
8267
+ ...status === void 0 ? {} : { status }
6680
8268
  };
6681
8269
  }
6682
8270
  /** Resolve once every queued refresh has settled, including coalesced work. */
@@ -6722,16 +8310,25 @@ var SessionChanges = class {
6722
8310
  * Self-heal a ledger whose data has gone stale.
6723
8311
  *
6724
8312
  * The panel polls `list`, and a poll is the one moment we know a human is
6725
- * looking at the answer. If the data is older than `maxAgeMs`, re-scan — so a
8313
+ * looking at the answer. If the data is older than the window, re-scan — so a
6726
8314
  * turn boundary this Host never delivered costs a few seconds of staleness
6727
8315
  * instead of a manual refresh.
6728
8316
  *
8317
+ * The window is ADAPTIVE ({@link selfHealMaxAge}): four times the last tracked
8318
+ * scan, clamped to 5–30s. A small repository therefore surfaces a manual edit
8319
+ * (one with no turn event behind it) within seconds instead of the old fixed
8320
+ * half minute, while a monorepo keeps the old ceiling. The two `false` paths —
8321
+ * a scan already running, and data that is still fresh — are unchanged.
8322
+ *
8323
+ * @param maxAgeMs - explicit window; callers that know better (and the checks)
8324
+ * override the adaptive default and keep the old semantics exactly.
6729
8325
  * @returns whether a refresh was queued.
6730
8326
  */
6731
- touch(sessionId, maxAgeMs = 3e4) {
8327
+ touch(sessionId, maxAgeMs) {
6732
8328
  const ledger = this.ledgers.get(sessionId);
6733
8329
  if (ledger === void 0 || ledger.disposed || ledger.pending) return false;
6734
- if (ledger.at > 0 && Date.now() - ledger.at < maxAgeMs) return false;
8330
+ const windowMs = maxAgeMs ?? selfHealMaxAge(ledger.scanMs);
8331
+ if (ledger.at > 0 && Date.now() - ledger.at < windowMs) return false;
6735
8332
  this.schedule(ledger);
6736
8333
  return true;
6737
8334
  }
@@ -6782,6 +8379,7 @@ var SessionChanges = class {
6782
8379
  ledger.untracked = void 0;
6783
8380
  ledger.untrackedAt = 0;
6784
8381
  ledger.untrackedMs = void 0;
8382
+ ledger.scanMs = void 0;
6785
8383
  ledger.untrackedGivenUp = false;
6786
8384
  ledger.untrackedFailure = void 0;
6787
8385
  ledger.files = [];
@@ -6792,6 +8390,13 @@ var SessionChanges = class {
6792
8390
  ledger.at = 0;
6793
8391
  ledger.unavailable = void 0;
6794
8392
  ledger.startedAt = Date.now();
8393
+ ledger.pendingClose = void 0;
8394
+ ledger.turnAfter = void 0;
8395
+ ledger.turnAfterTruncated = false;
8396
+ ledger.turnDelta = void 0;
8397
+ ledger.turnBefore = void 0;
8398
+ ledger.turnBeforeTruncated = false;
8399
+ ledger.turnProvisional = false;
6795
8400
  }
6796
8401
  /**
6797
8402
  * Resolve (or rebind) the ledger for one session from its CURRENT cwd.
@@ -6855,6 +8460,7 @@ var SessionChanges = class {
6855
8460
  untracked: void 0,
6856
8461
  untrackedAt: 0,
6857
8462
  untrackedMs: void 0,
8463
+ scanMs: void 0,
6858
8464
  untrackedJob: void 0,
6859
8465
  turn: 0,
6860
8466
  files: [],
@@ -6867,6 +8473,14 @@ var SessionChanges = class {
6867
8473
  pending: false,
6868
8474
  queue: Promise.resolve(),
6869
8475
  dirty: false,
8476
+ pendingClose: void 0,
8477
+ turnAfter: void 0,
8478
+ turnAfterTruncated: false,
8479
+ turnDelta: void 0,
8480
+ turnBefore: void 0,
8481
+ turnBeforeTruncated: false,
8482
+ turnProvisional: false,
8483
+ turnDisabled: void 0,
6870
8484
  publishSeq: 0,
6871
8485
  disposed: false
6872
8486
  };
@@ -6900,15 +8514,24 @@ var SessionChanges = class {
6900
8514
  */
6901
8515
  async refresh(ledger) {
6902
8516
  if (ledger.disposed || ledger.root === "") return;
8517
+ const scanStartedAt = Date.now();
6903
8518
  const scanned = await this.scanTracked(ledger);
6904
8519
  if (ledger.disposed || scanned === void 0) return;
6905
8520
  if (ledger.root !== scanned.root) return;
8521
+ ledger.scanMs = Math.max(0, Date.now() - scanStartedAt);
6906
8522
  ledger.tracked = scanned.entries;
6907
8523
  await this.publish(ledger);
6908
8524
  this.kickUntracked(ledger);
6909
8525
  }
6910
- /** Recompute the panel's list from the scans currently known. */
6911
- async publish(ledger) {
8526
+ /**
8527
+ * Recompute the panel's list from the scans currently known.
8528
+ *
8529
+ * @param fromSlowScan - this publish was triggered by the `git ls-files
8530
+ * --others` walk. A turn delta closed before that walk landed is still
8531
+ * provisional: this flag is what lets it be re-derived once the turn's new
8532
+ * files are known (see `correctTurn`).
8533
+ */
8534
+ async publish(ledger, fromSlowScan = false) {
6912
8535
  if (ledger.disposed) return;
6913
8536
  const seq = ++ledger.publishSeq;
6914
8537
  const root = ledger.root;
@@ -6995,6 +8618,274 @@ var SessionChanges = class {
6995
8618
  ledger.truncated = truncated ? true : void 0;
6996
8619
  ledger.unavailable = listed.length > 0 && after.size === 0 ? "file contents could not be read from the host" : void 0;
6997
8620
  ledger.at = Date.now();
8621
+ if (ledger.pendingClose !== void 0) await this.closeTurn(ledger, root, seq, entries, listed, after, records, truncated);
8622
+ else if (fromSlowScan) await this.correctTurn(ledger, root, seq, entries, listed, after, records, truncated);
8623
+ }
8624
+ /**
8625
+ * Close one turn: compute "what did it change" and remember this close as the
8626
+ * next turn's starting point.
8627
+ *
8628
+ * The delta is defined against the PREVIOUS close, not the session baseline, so
8629
+ * a file the session changed in turn 1 and left alone in turn 2 must not appear
8630
+ * in turn 2's list — otherwise the view says the same work happened twice.
8631
+ * That is what `turnAfter` is for: it holds every listed path's text at the
8632
+ * moment the previous turn closed, and it is replaced (never merged) here.
8633
+ *
8634
+ * A failed `after` read leaves the boundary unconsumed, so the next publish
8635
+ * retries instead of recording a turn against "nothing".
8636
+ */
8637
+ async closeTurn(ledger, root, seq, entries, listed, after, records, truncated) {
8638
+ const turn = ledger.pendingClose;
8639
+ if (turn === void 0 || ledger.disposed) return;
8640
+ ledger.pendingClose = void 0;
8641
+ if (ledger.turnDisabled !== void 0) return;
8642
+ const known = ledger.turnAfter;
8643
+ const collected = await this.collectTurnSides(ledger, root, seq, listed, after, known);
8644
+ if (collected.kind === "retry") {
8645
+ ledger.pendingClose = turn;
8646
+ return;
8647
+ }
8648
+ if (collected.kind === "superseded") return;
8649
+ /**
8650
+ * A previous snapshot cut by the file cap cannot prove that a path MISSING
8651
+ * from it was clean — it may simply have been past the cap. Entries that were
8652
+ * listed then are still exact, so only the "newcomer = changed this turn"
8653
+ * inference is dropped, and the view says it is partial (`truncated`).
8654
+ */
8655
+ const partial = ledger.turnAfterTruncated;
8656
+ const previousUncorrected = ledger.turnProvisional;
8657
+ const built = this.buildTurnDelta(root, turn, collected.now, entries, records, known, partial, truncated);
8658
+ this.storeTurnDelta(ledger, built, previousUncorrected);
8659
+ if (built.overflow) return;
8660
+ ledger.turnBefore = known;
8661
+ ledger.turnBeforeTruncated = partial;
8662
+ ledger.turnProvisional = true;
8663
+ /**
8664
+ * This close becomes the next turn's starting point. Built from `listed`
8665
+ * ONLY: a path that left the dirty list is at its baseline, and the session
8666
+ * baseline is exactly what a re-appearance will be compared against — keeping
8667
+ * it here would cost a full re-read of every reverted file on every later
8668
+ * turn.
8669
+ */
8670
+ ledger.turnAfter = this.turnSnapshotOf(listed, collected.now);
8671
+ ledger.turnAfterTruncated = truncated;
8672
+ }
8673
+ /**
8674
+ * Re-derive the CURRENT turn's delta once the slow scan behind it has landed.
8675
+ *
8676
+ * A turn's new files are discovered by `git ls-files --others`, which runs
8677
+ * after the tracked scan by design and can land seconds later. Rebuilding the
8678
+ * same turn from the SAME "before" snapshot (kept in `turnBefore`) is what
8679
+ * makes those files appear in the turn they belong to instead of in the next
8680
+ * one. Guarded against the two ways this could lie: a newer turn boundary
8681
+ * (which supersedes this delta) and a root move.
8682
+ */
8683
+ async correctTurn(ledger, root, seq, entries, listed, after, records, truncated) {
8684
+ const delta = ledger.turnDelta;
8685
+ const before = ledger.turnBefore;
8686
+ if (!ledger.turnProvisional || delta === void 0) return;
8687
+ ledger.turnProvisional = false;
8688
+ if (ledger.turnDisabled !== void 0 || ledger.turn !== delta.turn) return;
8689
+ const collected = await this.collectTurnSides(ledger, root, seq, listed, after, before);
8690
+ if (collected.kind !== "ok") return;
8691
+ const partial = ledger.turnBeforeTruncated;
8692
+ const built = this.buildTurnDelta(root, delta.turn, collected.now, entries, records, before, partial, truncated);
8693
+ this.storeTurnDelta(ledger, built, false);
8694
+ if (built.overflow) return;
8695
+ const stored = ledger.turnDelta;
8696
+ if (stored !== void 0) stored.provisional = false;
8697
+ ledger.turnAfter = this.turnSnapshotOf(listed, collected.now);
8698
+ }
8699
+ /** Remember one close's sides for the next boundary (see `TurnSideText`). */
8700
+ turnSnapshotOf(listed, now) {
8701
+ const snapshot = /* @__PURE__ */ new Map();
8702
+ for (const entry of listed) {
8703
+ const side = now.get(entry.path);
8704
+ snapshot.set(entry.path, {
8705
+ text: side?.text ?? null,
8706
+ known: side?.known ?? false
8707
+ });
8708
+ }
8709
+ return snapshot;
8710
+ }
8711
+ /**
8712
+ * The "after" side of one turn close, in `display` space.
8713
+ *
8714
+ * Starts from the publish's own reads (every listed path), then reads the paths
8715
+ * the PREVIOUS close listed but this publish does not: those left the dirty
8716
+ * list (reverted to their baseline, deleted, restored), and without reading
8717
+ * them now the revert would be attributed to nobody — "the turn put the file
8718
+ * back" would look like "the turn changed nothing".
8719
+ *
8720
+ * @returns `ok` with the sides; `retry` when a read failed (the caller keeps
8721
+ * the turn boundary for the next publish); `superseded` when a root move or
8722
+ * a newer publish already owns the observation.
8723
+ */
8724
+ async collectTurnSides(ledger, root, seq, listed, after, known) {
8725
+ if (listed.length > 0 && after.size === 0) return { kind: "retry" };
8726
+ const now = /* @__PURE__ */ new Map();
8727
+ for (const entry of listed) {
8728
+ const side = after.get(entry.path);
8729
+ if (side === void 0) return { kind: "retry" };
8730
+ now.set(entry.path, turnSideOf(side));
8731
+ }
8732
+ const vanished = known === void 0 ? [] : [...known.keys()].filter((display) => !now.has(display));
8733
+ if (vanished.length === 0) return {
8734
+ kind: "ok",
8735
+ now
8736
+ };
8737
+ const reads = await this.readPaths(ledger, vanished, "worktree");
8738
+ if (ledger.disposed) return { kind: "superseded" };
8739
+ if (ledger.root !== root || ledger.publishSeq !== seq) return { kind: "superseded" };
8740
+ if (reads.size === 0) return { kind: "retry" };
8741
+ for (const display of vanished) {
8742
+ const side = reads.get(display);
8743
+ if (side === void 0) return { kind: "retry" };
8744
+ now.set(display, turnSideOf(side));
8745
+ }
8746
+ return {
8747
+ kind: "ok",
8748
+ now
8749
+ };
8750
+ }
8751
+ /**
8752
+ * Compare one turn's before/after sides into panel rows plus cached hunks.
8753
+ *
8754
+ * The comparison rules are the ones the whole-session `publish` uses (binary
8755
+ * and cap-withheld bytes carry 0/0 counts, a creation has no reverse patch,
8756
+ * hunks come from the same Myers implementation), so a row means the same
8757
+ * thing in both views.
8758
+ */
8759
+ buildTurnDelta(root, turn, now, entries, records, known, partial, capTruncated) {
8760
+ const statusOf = /* @__PURE__ */ new Map();
8761
+ for (const entry of entries) statusOf.set(entry.path, panelStatus(entry.status));
8762
+ const budget = this.deps.turnPatchBytes ?? MAX_TURN_PATCH_BYTES;
8763
+ const files = [];
8764
+ const turnRecords = /* @__PURE__ */ new Map();
8765
+ let added = 0;
8766
+ let deleted = 0;
8767
+ let bytes = 0;
8768
+ let incomplete = partial || capTruncated;
8769
+ for (const [display, side] of now) {
8770
+ const absolute = posixJoin(root, display);
8771
+ const record = records.get(absolute);
8772
+ const had = known !== void 0 && known.has(display);
8773
+ if (!had && (record === void 0 || partial)) continue;
8774
+ const previous = had ? known.get(display) : void 0;
8775
+ if (had && previous !== void 0 && previous.known === false) {
8776
+ incomplete = true;
8777
+ continue;
8778
+ }
8779
+ const before = had ? previous?.text ?? null : record?.before ?? null;
8780
+ if (had && before === side.text) continue;
8781
+ const binary = side.binary || record?.binary === true;
8782
+ const oversized = !binary && (side.truncated || record?.truncated === true);
8783
+ let fileAdded = 0;
8784
+ let fileDeleted = 0;
8785
+ let hunks = [];
8786
+ let patch = "";
8787
+ if (!binary && !oversized) {
8788
+ const result = diffText(before ?? "", side.text ?? "");
8789
+ fileAdded = result.added;
8790
+ fileDeleted = result.deleted;
8791
+ hunks = result.hunks;
8792
+ patch = before !== null && hunks.length > 0 ? filePatch(display, hunks) : "";
8793
+ if (patch !== "") bytes += Buffer.byteLength(patch, "utf8");
8794
+ for (const hunk of hunks) for (const line of hunk.lines) bytes += Buffer.byteLength(line, "utf8") + 1;
8795
+ }
8796
+ added += fileAdded;
8797
+ deleted += fileDeleted;
8798
+ const status = statusOf.get(display);
8799
+ const revert = patch === "" ? void 0 : "patch";
8800
+ files.push({
8801
+ path: absolute,
8802
+ display,
8803
+ added: fileAdded,
8804
+ deleted: fileDeleted,
8805
+ ...binary ? { binary: true } : {},
8806
+ ...oversized ? { oversized: true } : {},
8807
+ ...status === void 0 ? {} : { status },
8808
+ ...revert === void 0 ? {} : { revert }
8809
+ });
8810
+ turnRecords.set(absolute, {
8811
+ display,
8812
+ path: absolute,
8813
+ status,
8814
+ binary,
8815
+ oversized,
8816
+ hunks,
8817
+ before,
8818
+ after: side.text,
8819
+ filePatch: patch
8820
+ });
8821
+ }
8822
+ files.sort((left, right) => left.display.localeCompare(right.display));
8823
+ return {
8824
+ turn,
8825
+ files,
8826
+ added,
8827
+ deleted,
8828
+ records: turnRecords,
8829
+ bytes,
8830
+ overflow: bytes > budget,
8831
+ incomplete
8832
+ };
8833
+ }
8834
+ /**
8835
+ * Commit one built delta, degrading honestly when it blew the memory budget.
8836
+ *
8837
+ * Over budget the statistics are already computed and stay usable, but the
8838
+ * per-file hunks and patches are dropped and this session stops computing turn
8839
+ * views: keeping a half-filled snapshot would make the NEXT turn compare
8840
+ * against texts that belong to an older boundary.
8841
+ */
8842
+ storeTurnDelta(ledger, built, uncorrectedPrevious) {
8843
+ const truncated = built.incomplete || uncorrectedPrevious;
8844
+ if (!built.overflow) {
8845
+ ledger.turnDelta = {
8846
+ turn: built.turn,
8847
+ files: built.files,
8848
+ added: built.added,
8849
+ deleted: built.deleted,
8850
+ at: Date.now(),
8851
+ cached: true,
8852
+ reason: void 0,
8853
+ truncated: truncated ? true : void 0,
8854
+ provisional: true,
8855
+ records: built.records,
8856
+ bytes: built.bytes
8857
+ };
8858
+ return;
8859
+ }
8860
+ const reason = `the per-turn patches and hunk text exceed the ${this.deps.turnPatchBytes ?? MAX_TURN_PATCH_BYTES} byte memory budget; turn totals stay available without per-file hunks`;
8861
+ ledger.turnDelta = {
8862
+ turn: built.turn,
8863
+ files: built.files.map((file) => {
8864
+ const { revert: _revert, ...rest } = file;
8865
+ return rest;
8866
+ }),
8867
+ added: built.added,
8868
+ deleted: built.deleted,
8869
+ at: Date.now(),
8870
+ cached: false,
8871
+ reason,
8872
+ truncated: truncated ? true : void 0,
8873
+ provisional: false,
8874
+ records: /* @__PURE__ */ new Map(),
8875
+ bytes: built.bytes
8876
+ };
8877
+ this.disableTurn(ledger, reason);
8878
+ }
8879
+ /** Stop computing turn views for this session, saying why (sticky). */
8880
+ disableTurn(ledger, reason) {
8881
+ if (ledger.turnDisabled !== void 0) return;
8882
+ ledger.turnDisabled = reason;
8883
+ ledger.turnAfter = void 0;
8884
+ ledger.turnAfterTruncated = false;
8885
+ ledger.turnBefore = void 0;
8886
+ ledger.turnBeforeTruncated = false;
8887
+ ledger.turnProvisional = false;
8888
+ this.warn(`per-turn view disabled: ${reason}`);
6998
8889
  }
6999
8890
  /**
7000
8891
  * The cheap scan: tracked files whose working-tree bytes differ from the
@@ -7114,7 +9005,7 @@ var SessionChanges = class {
7114
9005
  ledger.untrackedFailure = void 0;
7115
9006
  ledger.untracked = parseUntrackedZ(scan.stdout);
7116
9007
  await this.absorbPreExisting(ledger);
7117
- await this.publish(ledger);
9008
+ await this.publish(ledger, true);
7118
9009
  })().catch((error) => this.warn(`untracked scan failed: ${messageOf(error)}`)).finally(() => {
7119
9010
  ledger.untrackedJob = void 0;
7120
9011
  });
@@ -7305,11 +9196,23 @@ function toAgentHostRow(host) {
7305
9196
  managedKey: host.managedKey,
7306
9197
  ...host.description !== void 0 ? { description: host.description } : {},
7307
9198
  tags: [...host.tags],
9199
+ proxy: host.proxy,
7308
9200
  createdAt: host.createdAt,
7309
9201
  updatedAt: host.updatedAt
7310
9202
  };
7311
9203
  }
7312
9204
  /**
9205
+ * One-line description of a host's effective route, for the agent table.
9206
+ *
9207
+ * `problem` is part of the value (not a separate column): a host whose jump target
9208
+ * was deleted is still listed, and the caller must see why it would fail.
9209
+ */
9210
+ function proxyLabel(proxy) {
9211
+ const target = proxy.target === void 0 ? "" : ` ${proxy.target.host}:${proxy.target.port}`;
9212
+ const route = proxy.mode === "proxy" ? `proxy${target}` : proxy.mode === "jump" ? `jump ${proxy.jumpVia ?? "?"}` : proxy.mode;
9213
+ return proxy.problem === void 0 ? route : `${route} (problem: ${proxy.problem})`;
9214
+ }
9215
+ /**
7313
9216
  * Render the host table.
7314
9217
  *
7315
9218
  * An empty list has TWO very different causes and they used to share one
@@ -7320,8 +9223,8 @@ function toAgentHostRow(host) {
7320
9223
  function renderHosts(hosts, query) {
7321
9224
  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`;
7322
9225
  return [
7323
- "alias | host | port | user | auth | key | tags | description",
7324
- "--- | --- | --- | --- | --- | --- | --- | ---",
9226
+ "alias | host | port | user | auth | key | proxy | tags | description",
9227
+ "--- | --- | --- | --- | --- | --- | --- | --- | ---",
7325
9228
  ...hosts.map((h) => [
7326
9229
  h.alias,
7327
9230
  h.host,
@@ -7329,6 +9232,7 @@ function renderHosts(hosts, query) {
7329
9232
  h.user,
7330
9233
  h.auth,
7331
9234
  h.auth === "key" ? h.keyReady ? "key-ok" : "key-missing" : "password",
9235
+ proxyLabel(h.proxy),
7332
9236
  h.tags.length > 0 ? h.tags.join(",") : "-",
7333
9237
  h.description ?? ""
7334
9238
  ].join(" | "))
@@ -7411,6 +9315,49 @@ function remoteHostsTool(deps) {
7411
9315
  items: { type: "string" },
7412
9316
  required: true
7413
9317
  },
9318
+ proxy: {
9319
+ type: "object",
9320
+ additionalProperties: false,
9321
+ required: true,
9322
+ properties: {
9323
+ mode: {
9324
+ type: "string",
9325
+ enum: [
9326
+ "inherit",
9327
+ "direct",
9328
+ "proxy",
9329
+ "jump"
9330
+ ],
9331
+ required: true
9332
+ },
9333
+ target: {
9334
+ type: "object",
9335
+ additionalProperties: false,
9336
+ properties: {
9337
+ kind: {
9338
+ type: "string",
9339
+ enum: ["http", "socks5"],
9340
+ required: true
9341
+ },
9342
+ host: {
9343
+ type: "string",
9344
+ required: true
9345
+ },
9346
+ port: {
9347
+ type: "integer",
9348
+ required: true
9349
+ },
9350
+ username: { type: "string" },
9351
+ hasPassword: {
9352
+ type: "boolean",
9353
+ required: true
9354
+ }
9355
+ }
9356
+ },
9357
+ jumpVia: { type: "string" },
9358
+ problem: { type: "string" }
9359
+ }
9360
+ },
7414
9361
  createdAt: {
7415
9362
  type: "integer",
7416
9363
  required: true