@hearsay-tools/squawk 0.19.0-dev.9100 → 0.19.0-dev.9110

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 (37) hide show
  1. package/dist/contract/hosts.d.ts +47 -5
  2. package/dist/contract/index.js +19 -1
  3. package/dist/features/hosts/bootstrap.d.ts +120 -0
  4. package/dist/features/hosts/bootstrap.js +469 -0
  5. package/dist/features/hosts/bootstrap.js.map +1 -0
  6. package/dist/features/hosts/cli.d.ts +13 -3
  7. package/dist/features/hosts/cli.js +199 -27
  8. package/dist/features/hosts/cli.js.map +1 -1
  9. package/dist/features/hosts/host-actions.d.ts +56 -0
  10. package/dist/features/hosts/host-actions.js +367 -0
  11. package/dist/features/hosts/host-actions.js.map +1 -0
  12. package/dist/features/hosts/host-server-cli.js +21 -3
  13. package/dist/features/hosts/host-server-cli.js.map +1 -1
  14. package/dist/features/hosts/host-server.d.ts +10 -1
  15. package/dist/features/hosts/host-server.js +74 -0
  16. package/dist/features/hosts/host-server.js.map +1 -1
  17. package/dist/features/hosts/index.d.ts +4 -2
  18. package/dist/features/hosts/index.js +14 -2
  19. package/dist/features/hosts/index.js.map +1 -1
  20. package/dist/features/hosts/registry.d.ts +28 -0
  21. package/dist/features/hosts/registry.js +42 -1
  22. package/dist/features/hosts/registry.js.map +1 -1
  23. package/dist/features/hosts/routes.d.ts +5 -3
  24. package/dist/features/hosts/routes.js +14 -7
  25. package/dist/features/hosts/routes.js.map +1 -1
  26. package/dist/features/hosts/ssh.d.ts +85 -0
  27. package/dist/features/hosts/ssh.js +271 -0
  28. package/dist/features/hosts/ssh.js.map +1 -0
  29. package/dist/features/hosts/supervisor.d.ts +191 -0
  30. package/dist/features/hosts/supervisor.js +620 -0
  31. package/dist/features/hosts/supervisor.js.map +1 -0
  32. package/dist/features/hosts/tunnel.d.ts +46 -0
  33. package/dist/features/hosts/tunnel.js +244 -0
  34. package/dist/features/hosts/tunnel.js.map +1 -0
  35. package/dist/features/webhooks/routes.d.ts +13 -13
  36. package/dist/server/runs-routes.d.ts +16 -16
  37. package/package.json +4 -4
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Safe OpenSSH command runner and argv/environment builders for remote hosts
3
+ * (spec § Architecture 2, hearsay-tools/squawk#4539).
4
+ *
5
+ * Security boundary (owner rule 2026-11-30: nothing is sent from one host to another):
6
+ * - Every SSH call passes `BatchMode=yes`, `ForwardAgent=no`, `ForwardX11=no`, `RequestTTY=no`,
7
+ * `SetEnv=_=` (OpenSSH first-match-wins clears any config `SetEnv`), `ControlMaster=no`,
8
+ * `ControlPath=none`, `ControlPersist=no`, `ForkAfterAuthentication=no`, and `--`.
9
+ * - Every SSH child runs with a minimal allowlisted local environment (`PATH`, `HOME`, `USER`,
10
+ * `LOGNAME`, `SSH_AUTH_SOCK`, `TMPDIR`). That scrubbed local environment is what blocks config
11
+ * `SendEnv` directives from transmitting main-host variables or credentials; a config `SendEnv`
12
+ * naming one of the six kept variables would still send it, which is acceptable because none is
13
+ * a credential (`SSH_AUTH_SOCK` is a local socket path and `ForwardAgent=no` blocks forwarding).
14
+ * - Every call has both an OpenSSH `ConnectTimeout` and a hard process deadline that kills the
15
+ * child on expiry or abort.
16
+ */
17
+ import { spawn } from 'node:child_process';
18
+ import { existsSync, realpathSync } from 'node:fs';
19
+ import { userInfo } from 'node:os';
20
+ import { join, resolve } from 'node:path';
21
+ export const SSH_CONNECT_TIMEOUT_SECONDS = 15;
22
+ export const SSH_KEEPALIVE_INTERVAL_SECONDS = 15;
23
+ export const SSH_KEEPALIVE_COUNT_MAX = 3;
24
+ export const SSH_PROBE_TIMEOUT_MS = 20_000;
25
+ export const SSH_INSTALL_TIMEOUT_MS = 180_000;
26
+ export const SSH_ENSURE_TIMEOUT_MS = 45_000;
27
+ export const SSH_STATUS_TIMEOUT_MS = 10_000;
28
+ export const SSH_CONTROL_TIMEOUT_MS = 30_000;
29
+ export const SSH_TUNNEL_READY_TIMEOUT_MS = 20_000;
30
+ const KILL_GRACE_MS = 1_000;
31
+ const MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
32
+ const MAX_REASON_CHARS = 300;
33
+ /**
34
+ * Only local variables required for `ssh` itself to resolve binaries, `~/.ssh/config`, and local
35
+ * agent keys (`ForwardAgent=no` ensures the agent socket is never forwarded).
36
+ */
37
+ export const SSH_ALLOWED_LOCAL_ENV_KEYS = [
38
+ 'PATH',
39
+ 'HOME',
40
+ 'USER',
41
+ 'LOGNAME',
42
+ 'SSH_AUTH_SOCK',
43
+ 'TMPDIR',
44
+ ];
45
+ /** Build the scrubbed local environment passed to every `ssh` child process. */
46
+ export function buildSshLocalEnv(baseEnv = process.env) {
47
+ const entries = [
48
+ ['PATH', baseEnv.PATH],
49
+ ['HOME', baseEnv.HOME],
50
+ ['USER', baseEnv.USER],
51
+ ['LOGNAME', baseEnv.LOGNAME],
52
+ ['SSH_AUTH_SOCK', baseEnv.SSH_AUTH_SOCK],
53
+ ['TMPDIR', baseEnv.TMPDIR],
54
+ ];
55
+ const env = {};
56
+ for (const [key, value] of entries) {
57
+ if (value !== undefined)
58
+ env[key] = value;
59
+ }
60
+ return env;
61
+ }
62
+ function canonicalPath(path) {
63
+ try {
64
+ return realpathSync(path);
65
+ }
66
+ catch {
67
+ return resolve(path);
68
+ }
69
+ }
70
+ /**
71
+ * OpenSSH reads `/etc/passwd`'s `pw_dir/.ssh/config` rather than `$HOME/.ssh/config`. When the
72
+ * caller explicitly overrides `HOME` to a different directory (compared by real path so a
73
+ * symlinked home is not treated as overridden) that holds `.ssh/config`, pass
74
+ * `-F <HOME>/.ssh/config` so `ssh` reads the same config file that `ssh-config.ts` reads.
75
+ */
76
+ export function resolveIsolatedSshConfigPath(baseEnv = process.env) {
77
+ const overrideHome = baseEnv.HOME?.trim();
78
+ if (!overrideHome)
79
+ return undefined;
80
+ let passwdHome;
81
+ try {
82
+ passwdHome = userInfo().homedir;
83
+ }
84
+ catch {
85
+ passwdHome = undefined;
86
+ }
87
+ if (passwdHome !== undefined && canonicalPath(overrideHome) === canonicalPath(passwdHome)) {
88
+ return undefined;
89
+ }
90
+ const candidate = join(overrideHome, '.ssh', 'config');
91
+ return existsSync(candidate) ? candidate : undefined;
92
+ }
93
+ function commonSshOptions(options = {}) {
94
+ const connectTimeoutSeconds = options.connectTimeoutSeconds ?? SSH_CONNECT_TIMEOUT_SECONDS;
95
+ return [
96
+ ...(options.sshConfigPath ? ['-F', options.sshConfigPath] : []),
97
+ '-o', 'BatchMode=yes',
98
+ '-o', 'ForwardAgent=no',
99
+ '-o', 'ForwardX11=no',
100
+ '-o', 'RequestTTY=no',
101
+ '-o', 'SetEnv=_=',
102
+ '-o', 'ControlMaster=no',
103
+ '-o', 'ControlPath=none',
104
+ '-o', 'ControlPersist=no',
105
+ '-o', 'ForkAfterAuthentication=no',
106
+ '-o', `ConnectTimeout=${connectTimeoutSeconds}`,
107
+ '-o', `ServerAliveInterval=${SSH_KEEPALIVE_INTERVAL_SECONDS}`,
108
+ '-o', `ServerAliveCountMax=${SSH_KEEPALIVE_COUNT_MAX}`,
109
+ ];
110
+ }
111
+ /** Build the OpenSSH argv for a single non-interactive remote command call. */
112
+ export function buildSshCommandArgv(sshAlias, remoteCommand, options = {}) {
113
+ return [
114
+ ...commonSshOptions(options),
115
+ '-o', 'ClearAllForwardings=yes',
116
+ '--',
117
+ sshAlias,
118
+ remoteCommand,
119
+ ];
120
+ }
121
+ /** Build the OpenSSH argv for a loopback port-forwarding tunnel (`-N -L`). */
122
+ export function buildSshTunnelArgv(sshAlias, localPort, remotePort, options = {}) {
123
+ return [
124
+ '-N',
125
+ ...commonSshOptions(options),
126
+ '-o', 'ExitOnForwardFailure=yes',
127
+ '-L', `127.0.0.1:${localPort}:127.0.0.1:${remotePort}`,
128
+ '--',
129
+ sshAlias,
130
+ ];
131
+ }
132
+ /** Return the first non-empty line of `stderr` (bounded), or `fallback` when stderr is empty. */
133
+ export function firstStderrLine(stderr, fallback) {
134
+ for (const raw of stderr.split(/\r?\n/)) {
135
+ const trimmed = raw.trim();
136
+ if (trimmed.length > 0) {
137
+ return trimmed.length > MAX_REASON_CHARS ? `${trimmed.slice(0, MAX_REASON_CHARS - 1)}…` : trimmed;
138
+ }
139
+ }
140
+ return fallback;
141
+ }
142
+ /** Terminate an SSH child cleanly (SIGTERM, then SIGKILL after a short grace). */
143
+ export function terminateSshChild(child, graceMs = KILL_GRACE_MS) {
144
+ if (child.exitCode !== null || child.signalCode !== null)
145
+ return Promise.resolve();
146
+ return new Promise((resolve) => {
147
+ let settled = false;
148
+ const done = () => {
149
+ if (settled)
150
+ return;
151
+ settled = true;
152
+ clearTimeout(killTimer);
153
+ resolve();
154
+ };
155
+ const killTimer = setTimeout(() => {
156
+ try {
157
+ child.kill('SIGKILL');
158
+ }
159
+ catch { /* already exited */ }
160
+ done();
161
+ }, graceMs);
162
+ killTimer.unref();
163
+ child.once('close', done);
164
+ child.once('error', done);
165
+ try {
166
+ child.kill('SIGTERM');
167
+ }
168
+ catch {
169
+ done();
170
+ }
171
+ });
172
+ }
173
+ function appendBounded(chunks, totalBytes, chunk) {
174
+ if (totalBytes.value >= MAX_OUTPUT_BYTES)
175
+ return;
176
+ const remaining = MAX_OUTPUT_BYTES - totalBytes.value;
177
+ const slice = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk;
178
+ chunks.push(slice);
179
+ totalBytes.value += slice.length;
180
+ }
181
+ function failureReason(timedOut, aborted, timeoutMs, code, signal, stderr, stdinError) {
182
+ if (aborted)
183
+ return 'SSH command aborted';
184
+ if (timedOut)
185
+ return `SSH command timed out after ${timeoutMs}ms`;
186
+ if (stdinError)
187
+ return firstStderrLine(stderr, stdinError.message);
188
+ const fallback = signal ? `SSH exited with signal ${signal}` : `SSH exited with code ${String(code ?? 'unknown')}`;
189
+ return firstStderrLine(stderr, fallback);
190
+ }
191
+ function collectChildOutput(child) {
192
+ const stdoutChunks = [];
193
+ const stderrChunks = [];
194
+ const stdoutBytes = { value: 0 };
195
+ const stderrBytes = { value: 0 };
196
+ child.stdout?.on('data', (chunk) => appendBounded(stdoutChunks, stdoutBytes, chunk));
197
+ child.stderr?.on('data', (chunk) => appendBounded(stderrChunks, stderrBytes, chunk));
198
+ child.stdin?.on('error', () => undefined);
199
+ return {
200
+ stdout: () => Buffer.concat(stdoutChunks).toString('utf8'),
201
+ stderr: () => Buffer.concat(stderrChunks).toString('utf8'),
202
+ };
203
+ }
204
+ function waitForChildExit(child) {
205
+ return new Promise((resolve) => {
206
+ child.once('error', (error) => resolve({ code: null, signal: null, spawnError: error }));
207
+ child.once('close', (code, signal) => resolve({ code, signal }));
208
+ });
209
+ }
210
+ async function runStdinStream(child, streamStdin, onError) {
211
+ if (!streamStdin || !child.stdin)
212
+ return undefined;
213
+ try {
214
+ await streamStdin(child.stdin, child);
215
+ return undefined;
216
+ }
217
+ catch (error) {
218
+ try {
219
+ child.stdin.destroy();
220
+ }
221
+ catch { /* ignore */ }
222
+ onError();
223
+ return error instanceof Error ? error : new Error(String(error));
224
+ }
225
+ }
226
+ /** Execute one remote command over SSH with strict env isolation, deadline, and abort support. */
227
+ export async function runSshCommand(sshAlias, remoteCommand, options) {
228
+ const deps = options.deps ?? {};
229
+ if (options.signal?.aborted) {
230
+ return { ok: false, code: null, signal: null, stdout: '', stderr: '', timedOut: false, aborted: true, reason: 'SSH command aborted' };
231
+ }
232
+ const spawnFn = deps.spawn ?? spawn;
233
+ const argv = buildSshCommandArgv(sshAlias, remoteCommand, {
234
+ connectTimeoutSeconds: deps.connectTimeoutSeconds,
235
+ sshConfigPath: resolveIsolatedSshConfigPath(deps.env),
236
+ });
237
+ const child = spawnFn(deps.sshBin ?? 'ssh', argv, {
238
+ env: buildSshLocalEnv(deps.env),
239
+ stdio: [options.streamStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],
240
+ });
241
+ const output = collectChildOutput(child);
242
+ let timedOut = false;
243
+ let aborted = false;
244
+ const stopChild = () => { void terminateSshChild(child); };
245
+ const timer = setTimeout(() => { timedOut = true; stopChild(); }, options.timeoutMs);
246
+ timer.unref();
247
+ const onAbort = () => { aborted = true; stopChild(); };
248
+ options.signal?.addEventListener('abort', onAbort, { once: true });
249
+ const exitPromise = waitForChildExit(child);
250
+ const stdinError = await runStdinStream(child, options.streamStdin, stopChild);
251
+ const { code, signal, spawnError } = await exitPromise;
252
+ clearTimeout(timer);
253
+ options.signal?.removeEventListener('abort', onAbort);
254
+ const stdout = output.stdout();
255
+ const stderr = output.stderr();
256
+ if (spawnError) {
257
+ return { ok: false, code: null, signal: null, stdout, stderr, timedOut, aborted, reason: firstStderrLine(stderr, spawnError.message) };
258
+ }
259
+ const ok = !timedOut && !aborted && !stdinError && code === 0;
260
+ return {
261
+ ok,
262
+ code,
263
+ signal,
264
+ stdout,
265
+ stderr,
266
+ timedOut,
267
+ aborted,
268
+ ...(ok ? {} : { reason: failureReason(timedOut, aborted, options.timeoutMs, code, signal, stderr, stdinError) }),
269
+ };
270
+ }
271
+ //# sourceMappingURL=ssh.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssh.js","sourceRoot":"","sources":["../../../src/features/hosts/ssh.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAAE,KAAK,EAAwC,MAAM,oBAAoB,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAG1C,MAAM,CAAC,MAAM,2BAA2B,GAAG,EAAE,CAAC;AAC9C,MAAM,CAAC,MAAM,8BAA8B,GAAG,EAAE,CAAC;AACjD,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,CAAC;AAEzC,MAAM,CAAC,MAAM,oBAAoB,GAAG,MAAM,CAAC;AAC3C,MAAM,CAAC,MAAM,sBAAsB,GAAG,OAAO,CAAC;AAC9C,MAAM,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;IAC9D,OAAO;QACL,EAAE;QACF,IAAI;QACJ,MAAM;QACN,MAAM;QACN,MAAM;QACN,QAAQ;QACR,OAAO;QACP,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,aAAa,CAAC,QAAQ,EAAE,OAAO,EAAE,OAAO,CAAC,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,CAAC;KACjH,CAAC;AACJ,CAAC"}
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Per-host connection supervisor and server-wide manager (spec § Architecture 2 & § 6,
3
+ * hearsay-tools/squawk#4539).
4
+ *
5
+ * - Zero config: when `<config>/hosts.json` is absent or empty, zero supervisors, zero timers,
6
+ * and zero SSH processes are created.
7
+ * - Single operation slot per host: serializes automatic `ensure`, connected pause-status polls,
8
+ * and explicit `stop`/`start`/`update` calls on the main server.
9
+ * - Backoff: 2 s initial, 2x exponential, 60 s cap, +-25% jitter (min 500 ms), reset after 30 s
10
+ * stable connection.
11
+ * - Paused host: slow check every 300 s and on demand (at most once per 30 s per host); runs
12
+ * `ensure` and therefore cannot start a server while the pause record exists.
13
+ * - Operator-action states (`needs-node`, `version-mismatch`, `not-hosted`, `identity-changed`,
14
+ * `several-servers`, `cannot-persist`): retry every 300 s and on demand (at most once per 30 s
15
+ * per host).
16
+ * - Connected host (open point 6a): polls `hsq host-server status` every 30 s (10 s SSH deadline
17
+ * -> max 40 s detection bound when the machine answers) so a remote `hsq host stop` pauses the
18
+ * host even when the SSH tunnel stays open, and a stopped remote server triggers reconnect.
19
+ * - Decision 10: on a normal stop of the main server, local tunnel children end with it; it never
20
+ * stops a remote Squawk server.
21
+ */
22
+ import { type HostState } from '../../contract/index.js';
23
+ import type { Home } from '../../home/home.ts';
24
+ import type { ServerPluginContext } from '../../core/server-hook-registry.ts';
25
+ import { type HostBootstrapDeps } from './bootstrap.ts';
26
+ export declare const SUPERVISOR_INITIAL_BACKOFF_MS = 2000;
27
+ export declare const SUPERVISOR_MAX_BACKOFF_MS = 60000;
28
+ export declare const SUPERVISOR_MIN_BACKOFF_MS = 500;
29
+ export declare const SUPERVISOR_BACKOFF_JITTER_RATIO = 0.25;
30
+ export declare const SUPERVISOR_STABLE_RESET_MS = 30000;
31
+ export declare const SUPERVISOR_PAUSED_CHECK_INTERVAL_MS = 300000;
32
+ export declare const SUPERVISOR_OPERATOR_ACTION_RETRY_MS = 300000;
33
+ export declare const SUPERVISOR_ON_DEMAND_COOLDOWN_MS = 30000;
34
+ export declare const SUPERVISOR_CONNECTED_PAUSE_CHECK_INTERVAL_MS = 30000;
35
+ export interface HostRuntimeSnapshot {
36
+ readonly hostId: string;
37
+ readonly state: HostState;
38
+ readonly reason?: string | undefined;
39
+ readonly localPort?: number | undefined;
40
+ readonly remotePort?: number | undefined;
41
+ readonly ownership?: 'managed' | 'unmanaged' | undefined;
42
+ readonly managedByStarter?: boolean | undefined;
43
+ readonly remoteVersion?: string | undefined;
44
+ readonly remoteInstallId?: string | undefined;
45
+ readonly updatedAt: string;
46
+ }
47
+ export interface HostStateChangeEvent {
48
+ readonly hostId: string;
49
+ readonly previousState: HostState | undefined;
50
+ readonly state: HostState;
51
+ readonly reason?: string | undefined;
52
+ readonly localPort?: number | undefined;
53
+ readonly updatedAt: string;
54
+ }
55
+ export type HostStateChangeListener = (event: HostStateChangeEvent) => void;
56
+ export interface HostSupervisorOptions {
57
+ bootstrapDeps?: HostBootstrapDeps | undefined;
58
+ initialBackoffMs?: number | undefined;
59
+ maxBackoffMs?: number | undefined;
60
+ minBackoffMs?: number | undefined;
61
+ jitterRatio?: number | undefined;
62
+ stableResetMs?: number | undefined;
63
+ pausedCheckIntervalMs?: number | undefined;
64
+ operatorActionRetryMs?: number | undefined;
65
+ onDemandCooldownMs?: number | undefined;
66
+ connectedPauseCheckIntervalMs?: number | undefined;
67
+ nowMs?: (() => number) | undefined;
68
+ random?: (() => number) | undefined;
69
+ onStateChange?: HostStateChangeListener | undefined;
70
+ onStale?: (() => void) | undefined;
71
+ }
72
+ export interface BackoffOptions {
73
+ initialMs?: number | undefined;
74
+ maxMs?: number | undefined;
75
+ minMs?: number | undefined;
76
+ jitterRatio?: number | undefined;
77
+ random?: (() => number) | undefined;
78
+ }
79
+ /** Unjittered exponential backoff base for `attempt` (`0` -> initial, capped at `maxMs`). */
80
+ export declare function computeBackoffBaseMs(attempt: number, options?: Pick<BackoffOptions, 'initialMs' | 'maxMs'>): number;
81
+ /** Jittered capped exponential backoff (`+-25%`, clamped to `[minMs, maxMs]`). */
82
+ export declare function computeJitteredBackoffMs(attempt: number, options?: BackoffOptions): number;
83
+ /**
84
+ * Supervises one saved remote host: owns its tunnel child, single operation slot, backoff
85
+ * schedule, rate-limited on-demand checks (paused and operator-action states), and connected
86
+ * status polling.
87
+ */
88
+ export declare class HostSupervisor {
89
+ readonly hostId: string;
90
+ private readonly home;
91
+ private readonly opts;
92
+ private readonly trackedAlias;
93
+ private readonly trackedPort;
94
+ private snapshot;
95
+ private tunnel;
96
+ private lastProbe;
97
+ private started;
98
+ private disposed;
99
+ private backoffAttempt;
100
+ private lastRateLimitedCheckAtMs;
101
+ private retryTimer;
102
+ private stableTimer;
103
+ private connectedPauseTimer;
104
+ private activeAbort;
105
+ private inFlightEnsure;
106
+ private opChain;
107
+ private tunnelGeneration;
108
+ constructor(home: Home, hostId: string, options?: HostSupervisorOptions);
109
+ getSnapshot(): HostRuntimeSnapshot;
110
+ start(): void;
111
+ /**
112
+ * Gateway / on-demand entry point (spec § Architecture 2, S4):
113
+ * - Connected with live tunnel: returns immediately.
114
+ * - Paused or any operator-action state: starts SSH at most once per `onDemandCooldownMs`
115
+ * (default 30 s) per host; calls inside the window get the current state immediately.
116
+ * - Otherwise: awaits any in-flight attempt or triggers one immediate attempt right now.
117
+ */
118
+ ensureConnected(): Promise<HostRuntimeSnapshot>;
119
+ /** Stop timers, abort in-flight SSH commands, and close the local tunnel child (never stops remote server). */
120
+ dispose(): Promise<void>;
121
+ private enqueue;
122
+ private beginOperationAbort;
123
+ private endOperationAbort;
124
+ private isOnDemandRateLimited;
125
+ /**
126
+ * Re-read `<config>/hosts.json` on each tick (spec § Architecture 1):
127
+ * - Missing entry: close tunnel, stop timers, notify manager to remove this supervisor.
128
+ * - Changed alias or port: close old tunnel immediately, notify manager to reconcile and reconnect.
129
+ */
130
+ private checkEntryFreshness;
131
+ private triggerEnsure;
132
+ private runAutomaticEnsure;
133
+ private applyBootstrapResult;
134
+ private adoptConnectedTunnel;
135
+ private nextBackoffDelayMs;
136
+ private scheduleConnectedPauseCheck;
137
+ /**
138
+ * Open point 6a: poll `hsq host-server status --starter-id <mainInstallId> --json` while
139
+ * connected so a remote `hsq host stop` pauses even an unmanaged server within the stated bound,
140
+ * and a crashed/stopped remote server triggers reconnect even if SSH `-N -L` stays open.
141
+ */
142
+ private runConnectedPauseCheck;
143
+ private handleConnectedStatus;
144
+ private enterClosedOperatorState;
145
+ private enterClosedPausedState;
146
+ private closeActiveTunnel;
147
+ private scheduleRetry;
148
+ private clearRetryTimer;
149
+ private clearConnectedPauseTimer;
150
+ private clearStableAndPauseTimers;
151
+ private clearTimers;
152
+ private transition;
153
+ }
154
+ /**
155
+ * Owns one `HostSupervisor` per saved host for a running Squawk server.
156
+ * Zero hosts -> zero supervisors, zero timers, zero SSH processes.
157
+ *
158
+ * Exposes `ensureConnected(hostId)` for S4's gateway and `onStateChange(listener)` for S5's
159
+ * workspace event publisher.
160
+ */
161
+ export declare class HostSupervisorManager {
162
+ private readonly home;
163
+ private readonly options;
164
+ private readonly supervisors;
165
+ private readonly listeners;
166
+ private running;
167
+ constructor(home: Home, options?: HostSupervisorOptions);
168
+ isRunning(): boolean;
169
+ supervisorCount(): number;
170
+ /** Subscribe to every host state or reason change (S5 hooks workspace events here). */
171
+ onStateChange(listener: HostStateChangeListener): () => void;
172
+ /** Start supervision for every saved host. Creates nothing when `hosts.json` is empty or absent. */
173
+ start(): void;
174
+ /** Stop every supervisor and close every local tunnel child. Never stops remote Squawk servers. */
175
+ stop(): Promise<void>;
176
+ /** Synchronize supervisors with `<config>/hosts.json` (starts added, restarts edited, disposes removed). */
177
+ reconcile(): void;
178
+ getState(hostId: string): HostRuntimeSnapshot | undefined;
179
+ /**
180
+ * Gateway entry point (S4): returns `undefined` for an unknown host, or triggers/awaits an
181
+ * on-demand connect attempt (respecting the 30 s cooldown in paused and operator-action states).
182
+ */
183
+ ensureConnected(hostId: string): Promise<HostRuntimeSnapshot | undefined>;
184
+ private ensureTrackedSupervisor;
185
+ private createSupervisor;
186
+ }
187
+ /**
188
+ * Return the single `HostSupervisorManager` owned by a `ServerPluginContext`.
189
+ * S4 (gateway) and S5 (workspace state-change events) obtain the server's host manager here.
190
+ */
191
+ export declare function getHostSupervisorManager(context: ServerPluginContext, options?: HostSupervisorOptions): HostSupervisorManager;