centralu 0.1.0-beta.4 → 0.1.0-beta.41

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.
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Stopping the host `serve` runs for a data folder, and moving one that runs in a network logon into the person's
3
+ * Windows sign-in (#1224). One module so the foreground `serve` (serve-run.mjs) and `--stop` (serve-detach.mjs) share
4
+ * the stop without importing each other.
5
+ */
6
+ import { readServeState, heldHere, lockHolderPid, readServePid } from './serve-files.mjs'
7
+ import { DEFAULT_SERVE_PORT } from './serve-port.mjs'
8
+ import { protocolVersionOf, hostProvesOf, probeHost, askHostToStop, askHostRpc } from './serve-host.mjs'
9
+ import { ownLogon } from './serve-windows.mjs'
10
+ import { isAlive, say, sleep, waitUntil } from './serve-util.mjs'
11
+
12
+ /**
13
+ * Asks the host serve runs for `dataDir` to stop over its own socket and waits until it has, so its shutdown runs (its
14
+ * agents, terminals and app processes stopped in order, the store closed). Measured on Windows: killing the
15
+ * WMI-started launcher ended the host 143 ms later with no "shutting down" line, because the host sits in libuv's
16
+ * kill-on-close job object; so on Windows killing is the last resort, not the way.
17
+ *
18
+ * Then, only for a host that did not go: posix SIGTERM to the launcher (which passes it to the host, the same clean
19
+ * stop), and on Windows ending the host. A host from before `host.stop` gets that too. The launcher ends with its host;
20
+ * one still there afterwards is ended.
21
+ *
22
+ * Only the processes serve.pid and host.lock name, and only while they agree with each other and the host answered
23
+ * with this folder's token: a stale pid is never signalled.
24
+ *
25
+ * `{ ok, wasRunning, how?, message? }`, the `--stop` line's `stop`. With `ifIdle` (#1224, the hand-over) the host stops only
26
+ * when nothing runs there, and `{ ok: false, busy: true }` says it did not.
27
+ */
28
+ export async function stopServedHost({ dataDir, entry, platform = process.platform, ifIdle = false, timeoutMs = 30_000, graceMs = 15_000, kill = (pid, sig) => process.kill(pid, sig) }) {
29
+ const state = readServeState(dataDir)
30
+ if (!state) return { ok: true, wasRunning: false, message: `no centralu serve has run for ${dataDir}` }
31
+ const port = state.port ?? DEFAULT_SERVE_PORT
32
+ const installed = protocolVersionOf(entry) ?? 0
33
+ const prove = hostProvesOf(entry)
34
+ const probe = () => probeHost({ port, token: state.token, protocolVersion: installed, prove })
35
+ const first = await probe()
36
+ if (!heldHere(first, dataDir)) return { ok: true, wasRunning: false, message: `centralu serve is not running for ${dataDir}` }
37
+
38
+ const hostPid = lockHolderPid(dataDir)
39
+ const launcher = readServePid(dataDir)
40
+ // serve.pid is only believed when it names the host that holds the folder now
41
+ const launcherPid = launcher && hostPid && launcher.hostPid === hostPid ? launcher.pid : null
42
+ const down = async () => !(await probe()).running && !(hostPid && isAlive(hostPid))
43
+
44
+ let asked = await askHostToStop({ port, token: state.token, protocolVersion: first.protocolVersion ?? installed, prove, ifIdle })
45
+ if (!asked.ok && asked.protocolVersion !== undefined) asked = await askHostToStop({ port, token: state.token, protocolVersion: asked.protocolVersion, prove, ifIdle })
46
+ // `ifIdle` and it has work running (#1224): it was left as it is
47
+ if (asked.busy) return { ok: false, wasRunning: true, busy: true, message: asked.message }
48
+ let how = 'asked'
49
+ let stopped = asked.ok && (await waitUntil(down, timeoutMs))
50
+ let note = asked.ok ? null : `the host did not take the request to stop (${asked.message})`
51
+ if (!stopped) {
52
+ const target = platform !== 'win32' && launcherPid ? launcherPid : hostPid
53
+ if (target) {
54
+ how = platform === 'win32' ? 'ended' : 'signal'
55
+ try {
56
+ kill(target, 'SIGTERM')
57
+ } catch {
58
+ // gone in the meantime
59
+ }
60
+ stopped = await waitUntil(down, platform === 'win32' ? 5_000 : graceMs)
61
+ if (!stopped && hostPid && isAlive(hostPid)) {
62
+ how = 'ended'
63
+ try {
64
+ kill(hostPid, 'SIGKILL')
65
+ } catch {
66
+ // gone in the meantime
67
+ }
68
+ stopped = await waitUntil(down, 5_000)
69
+ }
70
+ }
71
+ if (how === 'ended') note = `${note ? `${note}; ` : ''}ended the host without its shutdown`
72
+ }
73
+ if (launcherPid && launcherPid !== process.pid && !(await waitUntil(() => !isAlive(launcherPid), 5_000))) {
74
+ try {
75
+ kill(launcherPid, 'SIGKILL')
76
+ } catch {
77
+ // gone in the meantime
78
+ }
79
+ }
80
+ if (!stopped) return { ok: false, wasRunning: true, how, message: `the host on 127.0.0.1:${port} is still running${note ? ` (${note})` : ''}` }
81
+ return { ok: true, wasRunning: true, how, ...(note ? { message: note } : {}) }
82
+ }
83
+
84
+ /** How long the hand-over waits for the host's work to end before it gives up and says so (#1224 review) */
85
+ export const HANDOVER_WAIT_MS = 30 * 60_000
86
+
87
+ /**
88
+ * The hand-over (#1224): a `serve` started in the person's Windows sign-in (the scheduled task, at sign-in or from
89
+ * `--detach`) found the folder held by a host that runs in a network logon, the one a hub's ssh started before anyone
90
+ * signed in. Git there cannot use the credentials saved in Windows, so the sign-in's host takes over, but only while that
91
+ * host has nothing running a person would lose. Windows has no keeper, so stopping a host ends what runs in it.
92
+ *
93
+ * The stop is `host.stop {ifIdle}`: the host itself checks and stops in one step, and from its yes on takes no new call,
94
+ * so a turn the hub starts cannot slip in between a check here and the stop (`lifecycle/stop-gate.ts` in agent-host).
95
+ * Until it says yes this asks again every `pollMs`, for `maxWaitMs` at most (30 minutes), and tells the host what it is
96
+ * doing (`host.handover`: `waiting`, then `gave_up`), which a hub linked to it shows on the machine's row. It ends early
97
+ * when that host goes by itself.
98
+ *
99
+ * Resolves true once the folder is free for this serve to start its host, false when there is nothing to move (not
100
+ * Windows, a host in any other logon or too old to say, this serve not in an interactive logon itself) or it gave up.
101
+ * The hub's link loses the machine between the stop and the new host's start, and reconnects by its usual backoff to the
102
+ * same port and token.
103
+ *
104
+ * `existing` is `probeHost`'s answer for the running host. `logonOf`, `stop`, `tell`, `pollMs`, `maxWaitMs` and `now` are
105
+ * parameters for tests.
106
+ */
107
+ export async function moveIntoSignIn({
108
+ dataDir,
109
+ entry,
110
+ env,
111
+ existing,
112
+ platform = process.platform,
113
+ logonOf = () => ownLogon(env),
114
+ stop = () => stopServedHost({ dataDir, entry, platform, ifIdle: true }),
115
+ tell = null,
116
+ pollMs = 30_000,
117
+ maxWaitMs = HANDOVER_WAIT_MS,
118
+ now = Date.now,
119
+ }) {
120
+ if (platform !== 'win32' || existing?.logon !== 'network') return false
121
+ if ((await logonOf()) !== 'interactive') return false
122
+ const state = readServeState(dataDir)
123
+ if (!state) return false
124
+ const port = state.port ?? DEFAULT_SERVE_PORT
125
+ const prove = hostProvesOf(entry)
126
+ const protocolVersion = existing.protocolVersion ?? protocolVersionOf(entry) ?? 0
127
+ const report = (handover) => (tell ?? ((h) => askHostRpc({ port, token: state.token, protocolVersion, prove, method: 'host.handover', params: { handover: h } })))(handover)
128
+ const pid = lockHolderPid(dataDir)
129
+ say(`the host running for ${dataDir}${pid ? ` (pid ${pid})` : ''} runs in a network logon (started over ssh), where Git cannot use the credentials saved in Windows; moving it into this Windows sign-in once nothing runs there`)
130
+ const t0 = now()
131
+ let waiting = false
132
+ for (;;) {
133
+ if (!(await probeHost({ port, token: state.token, protocolVersion, prove })).running) return true
134
+ const r = await stop()
135
+ if (r.ok) {
136
+ say(`stopped it${r.how && r.how !== 'asked' ? ` (${r.how})` : ''}; starting the host in this sign-in`)
137
+ return true
138
+ }
139
+ if (!r.busy) say(`could not stop it: ${r.message ?? 'no reason given'}; asking again later`)
140
+ if (!waiting) {
141
+ say('it has work running (a turn, an approval, a terminal or a command); waiting until it has none')
142
+ await report({ state: 'waiting', since: t0 })
143
+ waiting = true
144
+ }
145
+ if (now() - t0 >= maxWaitMs) {
146
+ await report({ state: 'gave_up', since: now() })
147
+ say(`gave up after ${Math.round(maxWaitMs / 60_000)} minutes: it still had work running. It moves into the sign-in at the next sign-in, or when a linked computer starts it again`)
148
+ return false
149
+ }
150
+ await sleep(pollMs)
151
+ }
152
+ }
@@ -0,0 +1,395 @@
1
+ /**
2
+ * The host `centralu serve` runs: how it is started, and talking to a running one over its own socket
3
+ * (a hello with the token, a proof first where the host gives one, `host.stop`).
4
+ */
5
+ import { createHmac, randomBytes } from 'node:crypto'
6
+ import { existsSync, readFileSync } from 'node:fs'
7
+ import { connect } from 'node:net'
8
+ import { dirname, join } from 'node:path'
9
+
10
+ /**
11
+ * The protocol a host folder speaks, from the `bundle-info.json` the bundler writes next to
12
+ * `main.mjs`. For a host run from source (`CENTRALU_HOST_ENTRY=…/src/main.ts`) there is no bundle
13
+ * info, so the constant is read where the bundler reads it. null when neither is there.
14
+ */
15
+ export function protocolVersionOf(entry) {
16
+ try {
17
+ const v = JSON.parse(readFileSync(join(dirname(entry), 'bundle-info.json'), 'utf8')).protocolVersion
18
+ if (Number.isInteger(v)) return v
19
+ } catch {
20
+ // not a bundle; try the source below
21
+ }
22
+ try {
23
+ const src = readFileSync(join(dirname(entry), '..', '..', 'protocol', 'src', 'envelope.ts'), 'utf8')
24
+ const m = /export const PROTOCOL_VERSION = (\d+)/.exec(src)
25
+ if (m) return Number(m[1])
26
+ } catch {
27
+ // nothing to read
28
+ }
29
+ return null
30
+ }
31
+
32
+ /**
33
+ * The `--connection` answer. The shape is the client's interface (docs/agent-host.md §4.7).
34
+ * `install` (additive, the line stays `v: 1`) says what runs this command (`installInfo`); `detach`
35
+ * is added by `--detach` only.
36
+ */
37
+ export function connectionLine({ port, token, version, protocolVersion, dataDir, hostRunning, install, autostart, detach, proof, stopped }) {
38
+ /*
39
+ * The options this serve takes that an older one refuses (#1223): a hub adds `--from <its name>` to `--detach` only
40
+ * when the line says so, since an older serve answers an option it does not know with an error. `window`: the
41
+ * desktop window on Windows uses this serve's host through `--window` only when it is listed (#1223 review)
42
+ */
43
+ const takes = ['from', 'window']
44
+ return JSON.stringify({
45
+ v: 1,
46
+ port,
47
+ token,
48
+ version,
49
+ protocolVersion,
50
+ dataDir,
51
+ hostRunning,
52
+ ...(install ? { install } : {}),
53
+ ...(autostart ? { autostart } : {}),
54
+ ...(detach ? { detach } : {}),
55
+ // The running host proves it holds the token before the hub sends it (#838); absent: the hub sends hello as before
56
+ ...(proof ? { proof: true } : {}),
57
+ // The person stopped the host here, and when (#1143, `readStopped`); absent: an older serve, or no such stop
58
+ ...(stopped ? { stopped } : {}),
59
+ takes,
60
+ })
61
+ }
62
+
63
+ /**
64
+ * Where a `serve` was asked for from (#1223), for the host's `host.lock` (`CC_SERVE_FROM`): the hub's name `--from`
65
+ * gave, and the ssh client's address when this runs in an ssh session (OpenSSH's `SSH_CLIENT`, on Windows too). What a
66
+ * `--detach` found is carried to the launcher it starts (`CENTRALU_STARTED_FROM`), which runs outside the ssh session.
67
+ * Null when neither is known.
68
+ */
69
+ export function serveFrom(env, hub = null) {
70
+ const carried = parseStartedFrom(env.CENTRALU_STARTED_FROM)
71
+ if (carried) return carried
72
+ const ssh = String(env.SSH_CLIENT ?? env.SSH_CONNECTION ?? '').trim().split(/\s+/)[0] ?? ''
73
+ const from = {
74
+ ...(typeof hub === 'string' && FROM_NAME_RE.test(hub) ? { hub } : {}),
75
+ ...(SSH_ADDRESS_RE.test(ssh) ? { ssh } : {}),
76
+ }
77
+ return from.hub || from.ssh ? from : null
78
+ }
79
+
80
+ const FROM_NAME_RE = /^[A-Za-z0-9._-]{1,64}$/
81
+ /** An IPv4 or IPv6 address as OpenSSH writes it: digits, hex, dots and colons */
82
+ const SSH_ADDRESS_RE = /^[0-9A-Fa-f.:]{2,64}$/
83
+
84
+ function parseStartedFrom(raw) {
85
+ if (!raw) return null
86
+ try {
87
+ const v = JSON.parse(raw)
88
+ const from = {
89
+ ...(typeof v?.hub === 'string' && FROM_NAME_RE.test(v.hub) ? { hub: v.hub } : {}),
90
+ ...(typeof v?.ssh === 'string' && SSH_ADDRESS_RE.test(v.ssh) ? { ssh: v.ssh } : {}),
91
+ }
92
+ return from.hub || from.ssh ? from : null
93
+ } catch {
94
+ return null
95
+ }
96
+ }
97
+
98
+ /**
99
+ * The host's environment.
100
+ *
101
+ * - The token is in neither: arguments are readable by every user on the machine (`ps`), and a
102
+ * process's start environment by every process of its user for as long as it runs (`ps eww`,
103
+ * #502). `CC_HOST_TOKEN_ON_STDIN=1` tells the host it comes as the first line on its stdin
104
+ * (`tokenLine`, #538), which is a pipe to this launcher anyway (`--watch-parent`). A host bundle
105
+ * from before #538 reads only `CC_HOST_TOKEN`: given `legacyToken` (`takesTokenOnStdin` said no),
106
+ * it gets the token there, as before.
107
+ * - `CC_HOST_SOURCE` is the record `hello_ok.build` is made from (keeper-link.ts); without it a
108
+ * client could not see which version the host it reached is.
109
+ * - Headless: no `DISPLAY` / `WAYLAND_DISPLAY`. Nothing the host or an agent starts gets a screen
110
+ * to open a window or a keyring prompt on, so a tool that would ask falls back to its file store
111
+ * or fails with a message in the log instead of waiting on a dialog nobody can see.
112
+ * - The keeper's and dev mode's variables are dropped: this host is neither. So is
113
+ * `CENTRALU_MANAGED`, which is the launcher's business and would otherwise reach every agent.
114
+ * - `CC_SERVE=1` lets the host take `host.stop` (`--stop`); a host the app runs refuses it.
115
+ */
116
+ export function hostEnv(env, { dataDir, version, hostDir, legacyToken, from = null }) {
117
+ const out = { ...env }
118
+ for (const k of ['DISPLAY', 'WAYLAND_DISPLAY', 'CC_KEEPER', 'CC_FRONT_DOOR', 'CC_DEV', 'CC_HOST_TOKEN', 'CC_HOST_TOKEN_ON_STDIN', 'CC_HOST_SOURCE', 'CENTRALU_MANAGED', 'CENTRALU_STARTED_FROM', 'CC_SERVE_FROM', 'CC_STARTED_BY']) delete out[k]
119
+ // Who asked for this host, for its host.lock (#1223): a second host on the folder names it when refused
120
+ if (from) out.CC_SERVE_FROM = JSON.stringify(from)
121
+ out.CC_DATA_DIR = dataDir
122
+ // The host `host.stop` may end (`centralu serve --stop`): nothing else stops it in order on Windows
123
+ out.CC_SERVE = '1'
124
+ if (legacyToken === undefined) out.CC_HOST_TOKEN_ON_STDIN = '1'
125
+ else out.CC_HOST_TOKEN = legacyToken
126
+ out.CC_HOST_SOURCE = JSON.stringify({ version, bundlePath: hostDir })
127
+ return out
128
+ }
129
+
130
+ /**
131
+ * Whether the host at `entry` reads its token from stdin (#538): a bundle says so in `bundle-info.json`
132
+ * (`tokenOnStdin`), as the keeper reads it; a host run from source always does. `CENTRALU_HOST_ENTRY` can point at an
133
+ * older bundle, which would otherwise get no token and refuse every hello.
134
+ */
135
+ export function takesTokenOnStdin(entry) {
136
+ try {
137
+ return JSON.parse(readFileSync(join(dirname(entry), 'bundle-info.json'), 'utf8')).tokenOnStdin === 1
138
+ } catch {
139
+ // not a bundle: the source, which reads it
140
+ }
141
+ return !existsSync(join(dirname(entry), 'bundle-info.json'))
142
+ }
143
+
144
+ /** The first line on the host's stdin: the token (#538, the host's `readHandedToken`) */
145
+ export function tokenLine(token) {
146
+ return `${JSON.stringify({ token })}\n`
147
+ }
148
+
149
+ /**
150
+ * How to start the host.
151
+ *
152
+ * `--watch-parent` with stdin a pipe: if this launcher dies however it dies (SIGKILL included), the
153
+ * pipe closes and the host shuts down with its children, instead of living on unsupervised.
154
+ * `detached` on POSIX puts the host in its own process group, so the terminal's Ctrl+C reaches
155
+ * only this launcher, which passes one SIGINT to the host alone; the host then stops its own
156
+ * children in order. Without it the terminal would signal every agent at the same time as the
157
+ * host. Not on Windows: there `detached` means a new console, and Ctrl+C reaches the host through
158
+ * the console it shares with this launcher.
159
+ */
160
+ export function hostCommand(execPath, entry, { port, dataDir, platform }) {
161
+ return {
162
+ command: execPath,
163
+ args: [
164
+ // A source entry (development, tests) needs the TypeScript loader; a bundle does not.
165
+ ...(entry.endsWith('.ts') ? ['--import', 'tsx'] : []),
166
+ entry,
167
+ '--port',
168
+ String(port),
169
+ '--db',
170
+ join(dataDir, 'store.db'),
171
+ '--watch-parent',
172
+ ],
173
+ detached: platform !== 'win32',
174
+ }
175
+ }
176
+
177
+ /** The port from the host's ready line (`{"ready":true,"port":…,"token":…}`), null for any other line */
178
+ export function readyPort(line) {
179
+ try {
180
+ const v = JSON.parse(line)
181
+ return v?.ready === true && Number.isInteger(v.port) ? v.port : null
182
+ } catch {
183
+ return null
184
+ }
185
+ }
186
+
187
+ /**
188
+ * The protocol a host's `version_mismatch` refusal names, from either wording: this one's
189
+ * ("this host speaks protocol 2") or the one before it ("server 2, client 1"). null if neither.
190
+ */
191
+ export function mismatchServerVersion(message) {
192
+ const m = /host speaks protocol (\d+)|\bserver (\d+)/.exec(String(message ?? ''))
193
+ return m ? Number(m[1] ?? m[2]) : null
194
+ }
195
+
196
+ /**
197
+ * The protocol a `version_mismatch` refusal says the host speaks: `data.protocolVersion`, which the host sends for a
198
+ * program to read (server.ts), else the sentence (`mismatchServerVersion`). null when neither names one.
199
+ */
200
+ function mismatchProtocolOf(error) {
201
+ if (Number.isInteger(error?.data?.protocolVersion)) return error.data.protocolVersion
202
+ return mismatchServerVersion(error?.message)
203
+ }
204
+
205
+ /**
206
+ * Whether the installed host answers a `prove` (#838): a bundle says so in `bundle-info.json` (`hostProof`), a host run
207
+ * from source has `transport/host-proof.ts`. The connection line's `proof` is this, not a live answer: a program another
208
+ * account put on the port could otherwise answer the probe so as to make the line say no, and the hub send the token.
209
+ */
210
+ export function hostProvesOf(entry) {
211
+ try {
212
+ return JSON.parse(readFileSync(join(dirname(entry), 'bundle-info.json'), 'utf8')).hostProof === 1
213
+ } catch {
214
+ // not a bundle; try the source below
215
+ }
216
+ return existsSync(join(dirname(entry), 'transport', 'host-proof.ts'))
217
+ }
218
+
219
+ /** The answer a host holding `token` gives to a `prove` of `nonce` (the host's `hostProof`) */
220
+ function proofOf(token, nonce) {
221
+ return createHmac('sha256', token).update(`centralu host proof v1\0${nonce}`).digest('base64url')
222
+ }
223
+
224
+ /**
225
+ * Opens a socket to the host and says hello with the token, the way `probeHost` and `askHostToStop` do. With `prove`
226
+ * (the installed host can, `hostProvesOf`), the host first proves it holds the token (#838), and the token goes out only
227
+ * then: whatever else listens on the port (another account's program, while the host is down) never sees it.
228
+ * `on.message(m, ws)` gets every frame after the hello; `on.unproven()` runs when the proof did not come, `on.gone()`
229
+ * when the socket failed or closed.
230
+ */
231
+ function helloSocket({ port, token, protocolVersion, prove, WebSocketImpl, on }) {
232
+ const ws = new WebSocketImpl(`ws://127.0.0.1:${port}`)
233
+ const nonce = prove ? randomBytes(24).toString('base64url') : null
234
+ // Proving only once the socket is open: a port where nothing listens is gone, not unproven
235
+ let proving = false
236
+ const hello = () => ws.send(JSON.stringify({ kind: 'hello', token, protocolVersion: protocolVersion ?? 0 }))
237
+ ws.onopen = () => {
238
+ if (!prove) return hello()
239
+ proving = true
240
+ ws.send(JSON.stringify({ kind: 'prove', nonce }))
241
+ }
242
+ ws.onmessage = (ev) => {
243
+ let m
244
+ try {
245
+ m = JSON.parse(String(ev.data))
246
+ } catch {
247
+ m = null
248
+ }
249
+ if (proving) {
250
+ proving = false
251
+ if (m?.kind === 'proof' && m.nonce === nonce && m.mac === proofOf(token, nonce)) return hello()
252
+ return on.unproven()
253
+ }
254
+ if (m) on.message(m, ws)
255
+ }
256
+ ws.onerror = () => (proving ? on.unproven() : on.gone())
257
+ ws.onclose = () => (proving ? on.unproven() : on.gone())
258
+ return ws
259
+ }
260
+
261
+ /**
262
+ * Whether a host that holds this token answers on the port: a real hello, not a TCP connect, so a
263
+ * stranger's program on the same port does not count, and the answer carries the running host's
264
+ * own protocol and version (which differ from the installed package's after an `npm i -g` the
265
+ * host was not restarted for). With `prove` the host proves it holds the token first (#838).
266
+ *
267
+ * `{ running, protocolVersion?, version?, unproven? }`. `unproven`: something answered on the port but did not prove
268
+ * it holds the token, so it was not sent: another program, or a host from before #838 still running after an update
269
+ * (`heldHere` tells those apart by the data folder's lock). Node 22.4+ has a global WebSocket; on an older 22 this falls
270
+ * back to a TCP connect and reports only `running`.
271
+ */
272
+ export function probeHost({ port, token, protocolVersion, prove = false, timeoutMs = 2000, WebSocketImpl = globalThis.WebSocket }) {
273
+ if (typeof WebSocketImpl !== 'function') return tcpProbe(port, timeoutMs)
274
+ return helloExchange({
275
+ port, token, protocolVersion, prove, WebSocketImpl, timeoutMs,
276
+ timedOut: { running: false },
277
+ failed: () => ({ running: false }),
278
+ on: (done) => ({
279
+ unproven: () => done({ running: false, unproven: true }),
280
+ gone: () => done({ running: false }),
281
+ message: (m) => {
282
+ if (m.kind === 'hello_ok') {
283
+ done({
284
+ running: true,
285
+ protocolVersion: Number.isInteger(m.protocolVersion) ? m.protocolVersion : undefined,
286
+ version: typeof m.build?.version === 'string' ? m.build.version : undefined,
287
+ // Which Windows logon it runs in (#1224): a `network` one is moved into the sign-in (serve-handover.mjs)
288
+ ...(HOST_LOGONS.includes(m.logon) ? { logon: m.logon } : {}),
289
+ })
290
+ } else if (m.kind === 'res' && m.ok === false && m.error?.code === 'version_mismatch') {
291
+ // The token was right (it is checked first), so this is our host, on another protocol
292
+ done({ running: true, protocolVersion: mismatchProtocolOf(m.error) ?? undefined })
293
+ }
294
+ },
295
+ }),
296
+ })
297
+ }
298
+
299
+ /**
300
+ * One `helloSocket` exchange that ends once: with the first `done(result)` an `on` handler calls, with `timedOut`
301
+ * after `timeoutMs`, or with `failed(error)` when the socket cannot even be made. The socket is closed in every case.
302
+ */
303
+ function helloExchange({ timeoutMs, timedOut, failed, on, ...hello }) {
304
+ return new Promise((resolve) => {
305
+ let ws = null
306
+ let settled = false
307
+ const done = (result) => {
308
+ if (settled) return
309
+ settled = true
310
+ clearTimeout(timer)
311
+ try {
312
+ ws?.close()
313
+ } catch {
314
+ // already closed
315
+ }
316
+ resolve(result)
317
+ }
318
+ const timer = setTimeout(() => done(timedOut), timeoutMs)
319
+ try {
320
+ ws = helloSocket({ ...hello, on: on(done) })
321
+ } catch (e) {
322
+ done(failed(e))
323
+ }
324
+ })
325
+ }
326
+
327
+ function tcpProbe(port, timeoutMs) {
328
+ return new Promise((resolve) => {
329
+ const s = connect({ host: '127.0.0.1', port })
330
+ const done = (running) => {
331
+ s.destroy()
332
+ resolve({ running })
333
+ }
334
+ s.setTimeout(timeoutMs, () => done(false))
335
+ s.once('connect', () => done(true))
336
+ s.once('error', () => done(false))
337
+ })
338
+ }
339
+
340
+ /** The logons a host's `hello_ok.logon` may name (#1224) */
341
+ const HOST_LOGONS = ['interactive', 'network', 'batch', 'service']
342
+
343
+ /**
344
+ * One call to a running host (`method` with `params`), as `askHostToStop` makes it: a hello with the token, then the
345
+ * call. Its result, or null when it did not answer or refused. For `host.handover` (#1224)
346
+ */
347
+ export function askHostRpc({ port, token, protocolVersion, prove = false, method, params = {}, timeoutMs = 5000, WebSocketImpl = globalThis.WebSocket }) {
348
+ if (typeof WebSocketImpl !== 'function') return Promise.resolve(null)
349
+ return helloExchange({
350
+ port, token, protocolVersion, prove, WebSocketImpl, timeoutMs,
351
+ timedOut: null,
352
+ failed: () => null,
353
+ on: (done) => ({
354
+ unproven: () => done(null),
355
+ gone: () => done(null),
356
+ message: (m, ws) => {
357
+ if (m.kind === 'hello_ok') ws.send(JSON.stringify({ kind: 'rpc', id: 'call', method, params }))
358
+ else if (m.kind === 'res' && m.id === 'call') done(m.ok && m.result && typeof m.result === 'object' ? m.result : null)
359
+ else if (m.kind === 'res' && m.ok === false) done(null)
360
+ },
361
+ }),
362
+ })
363
+ }
364
+
365
+ /**
366
+ * Asks a running host to stop (`host.stop`, an additive RPC): a hello with the token, then the call.
367
+ * `{ ok: true }` once the host took it, `{ ok: false, message, protocolVersion? }` otherwise; the
368
+ * last names the host's protocol when the hello was refused for it, so the caller can ask again.
369
+ * `ifIdle` (#1224): only if nothing runs there, checked and acted on by the host in one step; `{ ok: false, busy: true }`
370
+ * when something does.
371
+ */
372
+ export function askHostToStop({ port, token, protocolVersion, prove = false, ifIdle = false, timeoutMs = 5000, WebSocketImpl = globalThis.WebSocket }) {
373
+ if (typeof WebSocketImpl !== 'function') return Promise.resolve({ ok: false, message: `Node ${process.version} has no WebSocket to ask with` })
374
+ // With `prove`, the token goes out only to a host that proved it holds it (#838)
375
+ return helloExchange({
376
+ port, token, protocolVersion, prove, WebSocketImpl, timeoutMs,
377
+ timedOut: { ok: false, message: 'no answer in time' },
378
+ failed: (e) => ({ ok: false, message: e.message }),
379
+ on: (done) => ({
380
+ unproven: () => done({ ok: false, message: 'what answers on the port did not prove it holds the token' }),
381
+ gone: () => done({ ok: false, message: 'the connection closed' }),
382
+ message: (m, ws) => {
383
+ if (m.kind === 'hello_ok') ws.send(JSON.stringify({ kind: 'rpc', id: 'stop', method: 'host.stop', params: ifIdle ? { ifIdle: true } : {} }))
384
+ else if (m.kind === 'res' && m.id === 'stop' && m.ok && m.result?.ok === false) {
385
+ // `ifIdle` and something runs there (#1224): nothing was changed
386
+ done({ ok: false, busy: true, message: 'it has work running', activity: m.result.busy ?? null, calls: m.result.calls ?? 0 })
387
+ } else if (m.kind === 'res' && m.id === 'stop') done(m.ok ? { ok: true } : { ok: false, message: m.error?.message ?? 'refused' })
388
+ else if (m.kind === 'res' && m.ok === false) {
389
+ const pv = m.error?.code === 'version_mismatch' ? mismatchProtocolOf(m.error) : null
390
+ done({ ok: false, message: m.error?.message ?? 'refused', ...(pv !== null ? { protocolVersion: pv } : {}) })
391
+ }
392
+ },
393
+ }),
394
+ })
395
+ }