dsh-remote-go 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/dist/client.js +1344 -2095
  2. package/dist/src/admission.js +3 -28
  3. package/dist/src/api.js +37 -99
  4. package/dist/src/atomic-json.js +32 -66
  5. package/dist/src/bootstrap.js +17 -27
  6. package/dist/src/connect/attach.js +3 -25
  7. package/dist/src/connect/bootstrap.js +2 -8
  8. package/dist/src/connect/failures.js +3 -18
  9. package/dist/src/connect/guards.js +13 -8
  10. package/dist/src/connect/launch.js +11 -21
  11. package/dist/src/connect/links.js +11 -27
  12. package/dist/src/connect/ownership.js +33 -114
  13. package/dist/src/connect/pipeline.js +61 -158
  14. package/dist/src/connect/reattach.js +20 -44
  15. package/dist/src/connect/registry.js +0 -1
  16. package/dist/src/connect/repair.js +8 -37
  17. package/dist/src/connect/restart.js +36 -97
  18. package/dist/src/connect/stop.js +16 -50
  19. package/dist/src/connect/transport.js +10 -18
  20. package/dist/src/connect/verify.js +3 -12
  21. package/dist/src/connect/watchdog.js +6 -38
  22. package/dist/src/connect-log.js +16 -41
  23. package/dist/src/connect-progress.js +13 -45
  24. package/dist/src/constants.js +2 -40
  25. package/dist/src/context.js +10 -31
  26. package/dist/src/diagnostics.js +56 -25
  27. package/dist/src/download-jobs.js +11 -20
  28. package/dist/src/errors.js +175 -190
  29. package/dist/src/events.js +20 -84
  30. package/dist/src/host-lifecycle.js +39 -175
  31. package/dist/src/host-registry.js +27 -78
  32. package/dist/src/host-runtime.js +0 -9
  33. package/dist/src/host-view.js +6 -29
  34. package/dist/src/index.js +15 -35
  35. package/dist/src/kernel-adapter.js +34 -80
  36. package/dist/src/key-files.js +10 -23
  37. package/dist/src/known-hosts.js +13 -34
  38. package/dist/src/layout.js +3 -20
  39. package/dist/src/local-download.js +94 -163
  40. package/dist/src/local-ssh.js +12 -19
  41. package/dist/src/local-version.js +35 -49
  42. package/dist/src/node/download.js +1 -4
  43. package/dist/src/node-runtime.js +19 -38
  44. package/dist/src/probe.js +6 -7
  45. package/dist/src/prompts.js +56 -128
  46. package/dist/src/proxy/cookies.js +26 -60
  47. package/dist/src/proxy/headers.js +30 -125
  48. package/dist/src/proxy/http.js +33 -41
  49. package/dist/src/proxy/index.js +20 -34
  50. package/dist/src/proxy/limits.js +4 -6
  51. package/dist/src/proxy/routes.js +10 -17
  52. package/dist/src/proxy/upgrade.js +27 -42
  53. package/dist/src/redact.js +14 -33
  54. package/dist/src/remote-files.js +9 -21
  55. package/dist/src/remote-path.js +21 -62
  56. package/dist/src/remote-proc.js +35 -103
  57. package/dist/src/remote-web/registry.js +10 -50
  58. package/dist/src/remote-web/resolve.js +23 -104
  59. package/dist/src/remote-web/start.js +27 -64
  60. package/dist/src/remote-web/stop.js +6 -25
  61. package/dist/src/request-trust.js +15 -32
  62. package/dist/src/runtime/dispatch.js +33 -143
  63. package/dist/src/runtime/effects.js +7 -17
  64. package/dist/src/runtime/events.js +1 -1
  65. package/dist/src/runtime/fsm.js +11 -61
  66. package/dist/src/runtime/rules.js +113 -198
  67. package/dist/src/secrets.js +15 -38
  68. package/dist/src/service.js +22 -128
  69. package/dist/src/settings.js +41 -42
  70. package/dist/src/ssh-config.js +22 -41
  71. package/dist/src/ssh-failures.js +23 -74
  72. package/dist/src/ssh-sftp.js +47 -86
  73. package/dist/src/ssh.js +95 -177
  74. package/dist/src/store.js +31 -48
  75. package/dist/src/tool-shared.js +17 -52
  76. package/dist/src/tools-exec-policy.js +33 -79
  77. package/dist/src/tools-exec.js +87 -151
  78. package/dist/src/tools-report.js +100 -167
  79. package/dist/src/tools.js +59 -133
  80. package/dist/src/tunnel.js +9 -27
  81. package/dist/src/util.js +19 -56
  82. package/dist/src/version.js +6 -12
  83. package/dist/src/watchdog-bus.js +0 -8
  84. package/dist/src/watchdog.js +7 -47
  85. package/package.json +1 -1
package/dist/src/tools.js CHANGED
@@ -1,23 +1,5 @@
1
- /**
2
- * The model-facing surface of this plugin: the read-only host list, plus the one entry that unlocks
3
- * the two heavier tools (`remote_host_report`, `remote_exec`) on demand.
4
- *
5
- * Why a reveal step at all: the plugin's whole surface would cost schemas on every step of every
6
- * session, while most conversations never touch a remote host. Only the tiny entry tool is offered
7
- * up front; it advertises the three real tools and unlocks them for the calling session.
8
- *
9
- * Lazy here is **per step, not late registration**: all four definitions are registered at mount,
10
- * but the two heavy ones carry a `when` condition. `@deepseek-ai/dsh-tools` evaluates that condition
11
- * once per step, before the step's tool batch (`ToolsService.resolve`), and a `false` result removes
12
- * the tool from both the model-facing declarations and dispatch — so a session that never reveals
13
- * never pays for the schemas, and the reveal's effect lands on the next step. The state is keyed by
14
- * the calling agent, which is what makes it a per-conversation decision instead of a process-wide
15
- * switch.
16
- *
17
- * The registration is deliberately split from the definitions: `tools.ts` owns the list and the
18
- * reveal, `tools-report.ts` the diagnosis report, `tools-exec.ts` the remote command, and
19
- * `tool-shared.ts` the one redaction/projection path all three cross.
20
- */
1
+ /** The model-facing surface: the host list plus the entry that unlocks `remote_host_report`/`remote_exec`. The three
2
+ * real tools sit behind a per-step `when` keyed by the calling agent, so their schemas are only paid after a reveal. */
21
3
  import { reportTool, REPORT_TOOL_NAME } from './tools-report.js';
22
4
  import { execTool, EXEC_TOOL_NAME } from './tools-exec.js';
23
5
  import { ADDRESS_LIMIT, ERROR_SCHEMA, ID_LIMIT, NAME_LIMIT, describeViewError, renderFailure, renderText, safeText, serviceError, } from './tool-shared.js';
@@ -25,38 +7,32 @@ export const LIST_TOOL_NAME = 'remote_hosts_list';
25
7
  export const REVEAL_TOOL_NAME = 'remote_tools';
26
8
  /** A result never carries more rows than this, so one call cannot flood the model's context. */
27
9
  const MAX_HOSTS = 500;
28
- /**
29
- * One whitelisted host row. `additionalProperties: false` is deliberate: a field added to the
30
- * projection without a declared slot fails the tool call loudly instead of leaking into a result.
31
- *
32
- * `username` and `port` are contract and not secrets (`host-view.ts` says so): without them the
33
- * model can see that a host exists but cannot name the endpoint it is talking about, which is what
34
- * the diagnosis report and the remote command need.
35
- */
36
- const HOST_ROW_SCHEMA = {
10
+ /** One schema member with its description; the kernel reads these descriptions verbatim. */
11
+ const str = (description) => ({ type: 'string', description });
12
+ const int = (description) => ({ type: 'integer', description });
13
+ const bool = (description) => ({ type: 'boolean', description });
14
+ /** One closed object schema: its members, the required ones, no undeclared key. */
15
+ const obj = (properties, required) => ({
37
16
  type: 'object',
38
- properties: {
39
- id: { type: 'string', description: 'Host id the host manager shows for the same host.' },
40
- label: { type: 'string', description: 'Display name of the host.' },
41
- state: {
42
- type: 'string',
43
- description: 'Lifecycle state: unconfigured / connecting / fingerprint-pending / conflict-pending / connected / disconnected / error.',
44
- },
45
- connected: { type: 'boolean', description: 'True when the SSH link, tunnel and remote UI are up.' },
46
- address: { type: 'string', description: 'Configured address or ~/.ssh/config alias, redacted and shortened.' },
47
- username: { type: 'string', description: 'SSH user the host entry connects as, when it names one.' },
48
- port: { type: 'integer', description: 'SSH port (22 when the host entry does not override it).' },
49
- lastError: { type: 'string', description: 'Last failure as "code: reason"; the reason is untrusted remote text.' },
50
- progressCode: { type: 'string', description: 'Connect progress code while an attempt is in flight.' },
51
- remoteVersion: { type: 'string', description: 'DSH version the remote reported, when connected.' },
52
- },
53
- required: ['id', 'label', 'state', 'connected'],
17
+ properties,
18
+ required,
54
19
  additionalProperties: false,
55
- };
56
- /**
57
- * Project one HostView for the model. Every field is picked by name; nothing is spread from the
58
- * client view or the stored entry, so a credential or a private-key path cannot ride along.
59
- */
20
+ });
21
+ // `additionalProperties: false` is deliberate: an undeclared field fails loudly instead of leaking, and `username`/
22
+ // `port` are contract, not secrets — without them the model cannot name the endpoint it is talking about.
23
+ const HOST_ROW_SCHEMA = obj({
24
+ id: str('Host id the host manager shows for the same host.'),
25
+ label: str('Display name of the host.'),
26
+ state: str('Lifecycle state: unconfigured / connecting / fingerprint-pending / conflict-pending / connected / disconnected / error.'),
27
+ connected: bool('True when the SSH link, tunnel and remote UI are up.'),
28
+ address: str('Configured address or ~/.ssh/config alias, redacted and shortened.'),
29
+ username: str('SSH user the host entry connects as, when it names one.'),
30
+ port: int('SSH port (22 when the host entry does not override it).'),
31
+ lastError: str('Last failure as "code: reason"; the reason is untrusted remote text.'),
32
+ progressCode: str('Connect progress code while an attempt is in flight.'),
33
+ remoteVersion: str('DSH version the remote reported, when connected.'),
34
+ }, ['id', 'label', 'state', 'connected']);
35
+ /** Project one HostView by picking every field by name, so a credential or key path cannot ride along. */
60
36
  function hostRow(view) {
61
37
  const id = safeText(view?.id, ID_LIMIT);
62
38
  if (id === null)
@@ -73,8 +49,8 @@ function hostRow(view) {
73
49
  const username = safeText(view?.username, NAME_LIMIT);
74
50
  if (username !== null)
75
51
  row.username = username;
76
- // A port is an endpoint fact, not a secret: project it only when it is a real TCP port, so a
77
- // hostile entry cannot turn the field into a string the model would paste into a command.
52
+ // A port is an endpoint fact, not a secret: project it only when it is a real TCP port, so a hostile
53
+ // entry cannot turn the field into a string the model would paste into a command.
78
54
  const port = view?.port;
79
55
  if (Number.isInteger(port) && port > 0 && port <= 65535)
80
56
  row.port = port;
@@ -89,10 +65,7 @@ function hostRow(view) {
89
65
  row.remoteVersion = remoteVersion;
90
66
  return row;
91
67
  }
92
- /**
93
- * Project rows in the switcher's order, stopping one row past the cap: the answer only needs to know
94
- * whether there *is* a next row, so a large list never pays for a full projection.
95
- */
68
+ /** Rows in the switcher's order, stopping one past the cap so a large list never pays for a full projection. */
96
69
  function hostRows(service, options = {}) {
97
70
  const state = service?.snapshot?.();
98
71
  const views = Array.isArray(state?.hosts) ? state.hosts : [];
@@ -140,10 +113,7 @@ const REVEAL_DESCRIPTION = [
140
113
  'Call it when the user asks about their remote DSH hosts, why a host fails to connect, or wants something read or run on one of them. It changes nothing on any host, opens no connection, and is idempotent; the unlocked tools become callable on the next step.',
141
114
  '中文:dsh-remote-go 的三个工具默认隐藏,调用本入口为当前会话解锁主机清单(只读)、体检报告(只读)与远端命令(写模式需人类在插件配置里打开)。它不碰主机、不建连接、可重复调用,解锁的工具在下一步可用。',
142
115
  ].join('\n');
143
- /**
144
- * Build the host list. `service` is the Host half's own service, so the model reads the same
145
- * snapshot the host switcher renders.
146
- */
116
+ /** Build the host list. `service` is the Host half's own service, so the model reads the snapshot the switcher renders. */
147
117
  function listTool(options) {
148
118
  const service = options.service;
149
119
  const logger = options.logger ?? console;
@@ -153,27 +123,19 @@ function listTool(options) {
153
123
  parameters: {
154
124
  type: 'object',
155
125
  properties: {
156
- includeDisconnected: {
157
- type: 'boolean',
158
- description: 'Include hosts that are not connected right now (default true).',
159
- },
126
+ includeDisconnected: bool('Include hosts that are not connected right now (default true).'),
160
127
  },
161
128
  additionalProperties: false,
162
129
  },
163
130
  output: {
164
- schema: {
165
- type: 'object',
166
- properties: {
167
- ok: { type: 'boolean' },
168
- hosts: { type: 'array', items: HOST_ROW_SCHEMA },
169
- count: { type: 'integer', description: 'Number of rows returned (at most 500).' },
170
- connected: { type: 'integer', description: 'Number of returned rows in the connected state.' },
171
- truncated: { type: 'boolean', description: 'True when more hosts exist than the 500-row cap returned.' },
172
- error: ERROR_SCHEMA,
173
- },
174
- required: ['ok'],
175
- additionalProperties: false,
176
- },
131
+ schema: obj({
132
+ ok: { type: 'boolean' },
133
+ hosts: { type: 'array', items: HOST_ROW_SCHEMA },
134
+ count: int('Number of rows returned (at most 500).'),
135
+ connected: int('Number of returned rows in the connected state.'),
136
+ truncated: bool('True when more hosts exist than the 500-row cap returned.'),
137
+ error: ERROR_SCHEMA,
138
+ }, ['ok']),
177
139
  render(_args, raw) {
178
140
  try {
179
141
  const value = (raw ?? null);
@@ -196,8 +158,7 @@ function listTool(options) {
196
158
  }
197
159
  },
198
160
  },
199
- // No `timeoutMs`: the body is one bounded in-memory read plus a synchronous projection, and this
200
- // tool cannot honour a cooperative cancellation it never awaits. Leave the deadline to the kernel.
161
+ // No `timeoutMs`: the body is one bounded in-memory read plus a sync projection and never awaits a cancellation.
201
162
  isConcurrencySafe: () => true,
202
163
  async execute(raw) {
203
164
  const args = (raw ?? {});
@@ -222,10 +183,7 @@ function listTool(options) {
222
183
  }
223
184
  /** The three tools the entry unlocks, in the order the model should reach them. */
224
185
  const GATED_NAMES = [LIST_TOOL_NAME, REPORT_TOOL_NAME, EXEC_TOOL_NAME];
225
- /**
226
- * Build the reveal entry. It owns no state of its own: `onReveal` is the callback `registerOn`
227
- * keeps, so what the entry reports and what the `when` conditions read cannot drift apart.
228
- */
186
+ /** Build the reveal entry: it owns no state, so what it reports and what the `when` conditions read cannot drift. */
229
187
  function revealTool(options) {
230
188
  const logger = options.logger ?? console;
231
189
  return {
@@ -233,18 +191,13 @@ function revealTool(options) {
233
191
  description: REVEAL_DESCRIPTION,
234
192
  parameters: { type: 'object', properties: {}, additionalProperties: false },
235
193
  output: {
236
- schema: {
237
- type: 'object',
238
- properties: {
239
- ok: { type: 'boolean' },
240
- revealed: { type: 'array', items: { type: 'string' } },
241
- available: { type: 'array', items: { type: 'string' } },
242
- note: { type: 'string' },
243
- error: ERROR_SCHEMA,
244
- },
245
- required: ['ok'],
246
- additionalProperties: false,
247
- },
194
+ schema: obj({
195
+ ok: { type: 'boolean' },
196
+ revealed: { type: 'array', items: { type: 'string' } },
197
+ available: { type: 'array', items: { type: 'string' } },
198
+ note: { type: 'string' },
199
+ error: ERROR_SCHEMA,
200
+ }, ['ok']),
248
201
  render(_args, raw) {
249
202
  try {
250
203
  const value = (raw ?? null);
@@ -290,8 +243,8 @@ function revealTool(options) {
290
243
  function toolsService(ctx) {
291
244
  try {
292
245
  const tools = typeof ctx?.get === 'function' ? ctx.get('tools') : null;
293
- // `get` answers `unknown` (the kernel lookup is untyped): the two casts restate the one
294
- // capability this module needs, and they erase, so the runtime check stays the original one.
246
+ // `get` answers `unknown`, so these casts restate the one capability this module needs; they erase, and the
247
+ // runtime check below is the original one.
295
248
  return tools && typeof tools.register === 'function' ? tools : null;
296
249
  }
297
250
  catch {
@@ -299,25 +252,14 @@ function toolsService(ctx) {
299
252
  return null;
300
253
  }
301
254
  }
302
- /**
303
- * Register every model tool on one context and hand back the disposer that removes them.
304
- *
305
- * All four definitions are registered here; the three real ones carry the `onDemand` condition, so
306
- * a session that never calls the reveal entry never sees them. A kernel that refuses one definition
307
- * costs that tool only: the others register, and the plugin keeps its host switcher and HTTP API
308
- * either way.
309
- */
255
+ /** Register every model tool on one context and hand back the disposer. Only the three real ones carry the `when`
256
+ * condition, so a kernel that refuses one costs that tool only. */
310
257
  function registerOn(ctx, tools, options, logger, revealed) {
311
258
  return ctx.effect(() => {
312
- /** One disposer per registered tool, in registration order. */
313
259
  const disposers = [];
314
260
  /** The names this apply really registered: a kernel that refuses one must not be advertised. */
315
261
  const added = new Set();
316
- /**
317
- * The `when` condition of the three real tools. The registry evaluates it per step and drops a
318
- * `false` result from both the declarations and dispatch, so an agent that never revealed never
319
- * sees a schema and cannot call a tool even by name.
320
- */
262
+ // The `when` of the three real tools: per step, so an agent that never revealed cannot call one even by name.
321
263
  const onDemand = (context) => {
322
264
  const agent = context?.agent;
323
265
  return typeof agent === 'object' && agent !== null && revealed.has(agent);
@@ -340,8 +282,7 @@ function registerOn(ctx, tools, options, logger, revealed) {
340
282
  add(listTool({ service: options.service, logger }), onDemand);
341
283
  add(reportTool({ service: options.service, logger }), onDemand);
342
284
  add(execTool({ service: options.service, logger, allowWrite: options.exec?.allowWrite === true }), onDemand);
343
- // The entry itself is never hidden: it is the only thing a fresh session sees, and it is how
344
- // the other three are discovered at all.
285
+ // The entry itself is never hidden: it is the only thing a fresh session sees, and how the others are found.
345
286
  add(revealTool({
346
287
  logger,
347
288
  onReveal: (agent) => {
@@ -364,28 +305,13 @@ function registerOn(ctx, tools, options, logger, revealed) {
364
305
  };
365
306
  }, 'dsh-remote-go: model tools');
366
307
  }
367
- /**
368
- * Register the model tools on the host composition and return the disposer that removes them. They
369
- * live only here (the plugin's Host half): the browser half is a UI bundle and the remote DSH never
370
- * loads this package, so a remote session cannot see them.
371
- *
372
- * `tools` is an optional service, never injected: a composition without it keeps the plugin — and
373
- * with it the host switcher and the HTTP API — alive, and merely loses the tools plus one log line.
374
- * The registration always goes through `ctx.inject(['tools'], …)`: cordis parks that child fiber
375
- * while `tools` is absent and re-applies it when the service appears *or is replaced*, so neither a
376
- * late start nor a reload can cost the tools. What `ctx.inject` returns is the fiber, not a
377
- * disposer; the function below disposes that fiber so unloading really unregisters them.
378
- * @param ctx - the plugin context (`webServer` injected; `tools` looked up by the kernel).
379
- * @param options - the service the tools read and the operator's write switch.
380
- * @returns unregisters the tools and releases the parked fiber.
381
- */
308
+ /** Register the model tools on the Host half and return their disposer. `tools` is optional: without it the plugin
309
+ * lives, losing the tools and one log line. `ctx.inject` parks a fiber that cordis re-applies when `tools` appears *or
310
+ * is replaced*, and what it returns is the fiber, not a disposer — so this function disposes the fiber. */
382
311
  export function registerHostTools(ctx, options) {
383
312
  const logger = options?.logger ?? console;
384
- /**
385
- * The reveal state belongs to the plugin instance, not to one apply: a replaced `tools` service
386
- * re-applies the fiber, and a WeakSet created inside the effect would silently re-hide the three
387
- * tools a session had already unlocked. A WeakSet keeps a disposed agent collectable.
388
- */
313
+ // The reveal state belongs to the plugin instance, not one apply: a replaced `tools` re-applies the fiber, and a
314
+ // WeakSet created inside the effect would re-hide tools a session had unlocked. A WeakSet keeps agents collectable.
389
315
  const revealed = new WeakSet();
390
316
  if (typeof ctx?.inject === 'function') {
391
317
  if (toolsService(ctx) === null) {
@@ -1,15 +1,7 @@
1
- /**
2
- * Local loopback TCP listener piped through the SSH transport; the guest points at it, so its cookies never mix with the local GUI's.
3
- */
1
+ /** Local loopback TCP listener piped through the SSH transport; the guest points at it, so its cookies never mix with the local GUI's. */
4
2
  import http from 'node:http';
5
3
  import net from 'node:net';
6
- /**
7
- * Ask the *local* listener whether it still serves, without trusting the SSH-side probe:
8
- * any HTTP answer (even 401/404) proves the tunnel forwards, while a refused/destroyed
9
- * socket means it is broken. Used before rebuilding a tunnel for a transient proxy failure.
10
- * @param localPort - tunnel's local port, if any.
11
- * @returns whether the listener answered.
12
- */
4
+ /** Ask the *local* listener whether it still serves, without trusting the SSH-side probe: any HTTP answer (even 401/404) proves the tunnel forwards, while a refused/destroyed socket means it is broken. */
13
5
  export function probeLoopback(localPort, options = {}) {
14
6
  const port = Number(localPort);
15
7
  if (!Number.isInteger(port) || port <= 0 || port > 65535)
@@ -37,8 +29,6 @@ export async function createTunnel(options) {
37
29
  const remoteHost = options.remoteHost ?? '127.0.0.1';
38
30
  const listenHost = options.listenHost ?? '127.0.0.1';
39
31
  const sockets = new Set();
40
- // The forwarded SSH channels this listener opened: a closed listener must destroy them too,
41
- // otherwise an established pipe keeps the (already released) SSH transport busy.
42
32
  const streams = new Set();
43
33
  let closed = false;
44
34
  const server = net.createServer((socket) => {
@@ -47,15 +37,12 @@ export async function createTunnel(options) {
47
37
  return;
48
38
  }
49
39
  sockets.add(socket);
50
- const cleanup = () => {
51
- sockets.delete(socket);
52
- };
53
- socket.once('close', cleanup);
54
- socket.once('error', cleanup);
40
+ socket.once('close', () => sockets.delete(socket));
41
+ socket.once('error', () => sockets.delete(socket));
55
42
  const ssh = options.ssh;
43
+ // A listener can outlive its transport if a caller leaks it; never throw from a net connection
44
+ // callback (an uncaught exception there ends the whole host process).
56
45
  if (!ssh) {
57
- // A listener can outlive its transport if a caller leaks it; never throw from a net
58
- // connection callback (an uncaught exception there ends the whole host process).
59
46
  socket.destroy();
60
47
  return;
61
48
  }
@@ -68,19 +55,14 @@ export async function createTunnel(options) {
68
55
  return;
69
56
  }
70
57
  streams.add(stream);
71
- const forget = () => {
72
- streams.delete(stream);
73
- };
74
- stream.once('close', forget);
75
- stream.once('error', forget);
58
+ stream.once('close', () => streams.delete(stream));
59
+ stream.once('error', () => streams.delete(stream));
76
60
  socket.pipe(stream).pipe(socket);
77
61
  stream.once('close', () => {
78
62
  if (!socket.destroyed)
79
63
  socket.end();
80
64
  });
81
- stream.once('error', () => {
82
- socket.destroy();
83
- });
65
+ stream.once('error', () => socket.destroy());
84
66
  })
85
67
  .catch((error) => {
86
68
  options.onError?.(error instanceof Error ? error : new Error(String(error)));
package/dist/src/util.js CHANGED
@@ -1,6 +1,3 @@
1
- /**
2
- * Small pure helpers shared by the host half, unit-tested with node:test.
3
- */
4
1
  export function sleep(ms) {
5
2
  return new Promise((resolve) => setTimeout(resolve, ms));
6
3
  }
@@ -21,22 +18,17 @@ export function isPlainObject(value) {
21
18
  return typeof value === 'object' && value !== null && !Array.isArray(value);
22
19
  }
23
20
  const LOG_LEVELS = { error: 0, warn: 1, info: 2, debug: 3 };
21
+ const LOOPBACK_NAMES = new Set(['localhost', '::1', '::ffff:127.0.0.1']);
24
22
  /** Prototype-chain names that must never be written by a merge. */
25
23
  const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
26
- /**
27
- * Recursively merge `patch` into `base` (arrays and scalars replace). Only keys
28
- * `base` declares are written, so untrusted input can change known values but
29
- * never invent a property or poison the prototype.
30
- */
24
+ /** Merge `patch` into `base` (arrays/scalars replace); only keys `base` declares are written, so untrusted input cannot invent a property or poison the prototype. */
31
25
  export function deepMerge(base, patch) {
32
26
  if (!isPlainObject(base) || !isPlainObject(patch))
33
27
  return (patch === undefined ? base : patch);
34
28
  const out = { ...base };
35
29
  for (const key of Object.keys(base)) {
36
- if (UNSAFE_KEYS.has(key))
37
- continue;
38
30
  const value = patch[key];
39
- if (value === undefined)
31
+ if (value === undefined || UNSAFE_KEYS.has(key))
40
32
  continue;
41
33
  out[key] = isPlainObject(value) && isPlainObject(base[key]) ? deepMerge(base[key], value) : value;
42
34
  }
@@ -59,48 +51,26 @@ export function parseSshDestination(raw) {
59
51
  const text = String(raw ?? '').trim();
60
52
  if (text === '')
61
53
  return { user: null, host: '', port: null };
62
- let user = null;
63
- let rest = text;
64
- const at = rest.lastIndexOf('@');
65
- if (at >= 0) {
66
- user = rest.slice(0, at);
67
- rest = rest.slice(at + 1);
68
- }
69
- let host = rest;
70
- let port = null;
54
+ const at = text.lastIndexOf('@');
55
+ const user = (at >= 0 ? text.slice(0, at) : '') || null;
56
+ const rest = at >= 0 ? text.slice(at + 1) : text;
71
57
  if (rest.startsWith('[')) {
72
58
  const close = rest.indexOf(']');
73
- if (close > 0) {
74
- host = rest.slice(1, close);
75
- const tail = rest.slice(close + 1);
76
- if (/^:\d+$/.test(tail))
77
- port = Number(tail.slice(1));
78
- }
79
- }
80
- else {
81
- const colon = rest.lastIndexOf(':');
82
- if (colon > 0 && rest.indexOf(':') === colon) {
83
- const maybePort = rest.slice(colon + 1);
84
- if (/^\d{1,5}$/.test(maybePort)) {
85
- host = rest.slice(0, colon);
86
- port = Number(maybePort);
87
- }
88
- }
59
+ const tail = close > 0 ? rest.slice(close + 1) : '';
60
+ const port = /^:\d+$/.test(tail) ? Number(tail.slice(1)) : null;
61
+ return { user, host: close > 0 ? rest.slice(1, close) : rest, port };
89
62
  }
90
- return { user: user || null, host, port };
63
+ const colon = rest.lastIndexOf(':');
64
+ const maybePort = rest.slice(colon + 1);
65
+ const port = colon > 0 && rest.indexOf(':') === colon && /^\d{1,5}$/.test(maybePort) ? Number(maybePort) : null;
66
+ return { user, host: port === null ? rest : rest.slice(0, colon), port };
91
67
  }
92
68
  export function isLoopbackHost(host) {
93
- if (!host)
94
- return false;
95
- const normalized = host
69
+ const normalized = (host ?? '')
96
70
  .trim()
97
71
  .toLowerCase()
98
72
  .replace(/^\[|\]$/g, '');
99
- if (normalized === 'localhost' || normalized === '::1')
100
- return true;
101
- if (normalized === '::ffff:127.0.0.1')
102
- return true;
103
- return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(normalized);
73
+ return LOOPBACK_NAMES.has(normalized) || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(normalized);
104
74
  }
105
75
  export function shellQuote(value) {
106
76
  return `'${String(value).replaceAll("'", `'\\''`)}'`;
@@ -109,14 +79,11 @@ export function headTail(text, max = 4000) {
109
79
  const value = String(text ?? '');
110
80
  if (value.length <= max)
111
81
  return value;
112
- const head = value.slice(0, Math.floor(max / 2));
113
- const tail = value.slice(-Math.floor(max / 2));
114
- return `${head}\n…\n${tail}`;
82
+ const half = Math.floor(max / 2);
83
+ return `${value.slice(0, half)}\n…\n${value.slice(-half)}`;
115
84
  }
116
85
  export function logVisible(level, threshold = 'info') {
117
- const rank = LOG_LEVELS[level] ?? LOG_LEVELS.info;
118
- const floor = LOG_LEVELS[threshold] ?? LOG_LEVELS.info;
119
- return rank >= floor;
86
+ return (LOG_LEVELS[level] ?? LOG_LEVELS.info) >= (LOG_LEVELS[threshold] ?? LOG_LEVELS.info);
120
87
  }
121
88
  /** Message of an unknown thrown value, so catch blocks need not spell the ternary. */
122
89
  export function messageOf(error) {
@@ -126,11 +93,7 @@ export function messageOf(error) {
126
93
  export function isPid(value) {
127
94
  return Number.isInteger(value) && value > 0;
128
95
  }
129
- /**
130
- * A promise that resolves at most once: through `settle`, or with `onTimeout()`
131
- * when the deadline passes first. `onSettled` runs before the promise resolves so
132
- * a caller can clear the pending slot it installed on both paths.
133
- */
96
+ /** A promise that resolves at most once: through `settle`, or with `onTimeout()` when the deadline passes first; `onSettled` runs before the resolution so a caller can clear the slot it installed on both paths. */
134
97
  export function createDecision(timeoutMs, onTimeout, onSettled) {
135
98
  let settle;
136
99
  const promise = new Promise((resolve) => {
@@ -1,16 +1,13 @@
1
- /**
2
- * Version parsing/comparison and the exact-version parity rule, covering the shapes DSH and Node publish (`0.2.2-rc.1`, `24.22.2`, optional `v`).
3
- */
1
+ /** Version parsing/comparison and the exact-version parity rule, covering the shapes DSH and Node publish (`0.2.2-rc.1`, `24.22.2`, optional `v`). */
4
2
  const VERSION_RE = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/;
5
3
  export function parseVersion(input) {
6
- if (typeof input !== 'string')
7
- return null;
8
- const match = VERSION_RE.exec(input.trim());
4
+ const text = typeof input === 'string' ? input.trim() : '';
5
+ const match = text === '' ? null : VERSION_RE.exec(text);
9
6
  if (!match)
10
7
  return null;
11
8
  const [, major, minor, patch, prerelease, build] = match;
12
9
  return {
13
- raw: input.trim(),
10
+ raw: text,
14
11
  major: Number(major),
15
12
  minor: Number(minor),
16
13
  patch: Number(patch),
@@ -25,11 +22,8 @@ export function normalizeVersion(input) {
25
22
  const core = `${parsed.major}.${parsed.minor}.${parsed.patch}`;
26
23
  return parsed.prerelease.length > 0 ? `${core}-${parsed.prerelease.join('.')}` : core;
27
24
  }
28
- /**
29
- * Semver identifier comparison: numeric identifiers sort before alphanumeric ones. The
30
- * pre-release list is `(string | number)[]` by spec, so the two `as number` assertions only
31
- * restore the branch `typeof` already proved — nothing is coerced.
32
- */
25
+ // Semver identifier comparison: numeric identifiers sort first. The two `as number` assertions only
26
+ // restore the branch `typeof` already proved — nothing is coerced.
33
27
  function compareIdentifiers(a, b) {
34
28
  const aNum = typeof a === 'number';
35
29
  const bNum = typeof b === 'number';
@@ -1,20 +1,12 @@
1
- /**
2
- * Create the one bus a service instance owns.
3
- * @param options - only the warn sink for a listener that throws.
4
- * @returns the bus.
5
- */
6
1
  export function createWatchdogBus(options = {}) {
7
2
  const listeners = new Set();
8
3
  return {
9
4
  publish(event) {
10
- // Snapshot: a listener that (un)subscribes while handling an event must not change the
11
- // iteration of the event being published.
12
5
  for (const listener of [...listeners]) {
13
6
  try {
14
7
  listener(event);
15
8
  }
16
9
  catch (error) {
17
- // A listener failure must never break the probe that published the event.
18
10
  options.warn?.('[dsh-remote-go] watchdog listener failed:', error);
19
11
  }
20
12
  }