centralu 0.1.0-beta.3 → 0.1.0-beta.30

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,246 @@
1
+ /**
2
+ * `centralu serve --detach` and `--stop`: starting serve outside the ssh session that asked, and
3
+ * stopping it in order (docs/plans/remote-hub.md §10.4).
4
+ */
5
+ import { spawn } from 'node:child_process'
6
+ import { existsSync, openSync, renameSync, writeSync } from 'node:fs'
7
+ import { userInfo } from 'node:os'
8
+ import { join } from 'node:path'
9
+ import { answerLine, isAlive, say, sayTo, runCaptured, tail, sleep } from './serve-util.mjs'
10
+ import { SERVE_LOG_FILE, serveDataDir, ensureServeState } from './serve-files.mjs'
11
+ import { askPowershell, detachHow, windowsArg, wmiScript, parseWmiAnswer, wmiBlockedMessage, windowsPowershell, windowsTool, wslDistro, wslUser } from './serve-windows.mjs'
12
+ import { CHILD_FLAG } from './serve-args.mjs'
13
+ import { startInSignIn } from './serve-autostart.mjs'
14
+ import { stopServedHost } from './serve-handover.mjs'
15
+ import { connectionLine, serveFrom } from './serve-host.mjs'
16
+ import { describe, runServe, serveFolder } from './serve-run.mjs'
17
+
18
+ /**
19
+ * What a detached launcher needs from the `--detach` that started it. A process created through WMI
20
+ * does not inherit this environment: it gets the account's default one. Everything else it needs
21
+ * (the token, the port) is in the data folder. Never a secret.
22
+ */
23
+ export const CARRIED_ENV = ['CC_DATA_DIR', 'CENTRALU_HOST_ENTRY', 'CENTRALU_MANAGED', 'CENTRALU_STARTED_FROM']
24
+
25
+ export function encodeChildSpec({ env, log }) {
26
+ const carried = {}
27
+ for (const k of CARRIED_ENV) if (typeof env[k] === 'string' && env[k]) carried[k] = env[k]
28
+ return Buffer.from(JSON.stringify({ log, env: carried }), 'utf8').toString('base64url')
29
+ }
30
+
31
+ /** `{ log, env }` from `--detached-child=`, only the carried variables; null when it is not one */
32
+ export function decodeChildSpec(raw) {
33
+ try {
34
+ const v = JSON.parse(Buffer.from(String(raw), 'base64url').toString('utf8'))
35
+ if (typeof v?.log !== 'string' || !v.log) return null
36
+ const env = {}
37
+ for (const k of CARRIED_ENV) if (typeof v.env?.[k] === 'string') env[k] = v.env[k]
38
+ return { log: v.log, env }
39
+ } catch {
40
+ return null
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Starts the launcher outside this session (`detachHow`). `{ ok: true, pid, exited?, alive? }` once
46
+ * something was created, `{ ok: false, blocked, message }` when nothing was: `blocked` is the WMI
47
+ * refusal the hub falls back from.
48
+ */
49
+ export async function startDetached({ how, execPath, args, env, cwd }) {
50
+ if (how === 'setsid') {
51
+ return await new Promise((resolve) => {
52
+ let child
53
+ try {
54
+ child = spawn(execPath, args, { detached: true, stdio: 'ignore', cwd, env, windowsHide: true })
55
+ } catch (e) {
56
+ return resolve({ ok: false, blocked: false, message: `could not start ${execPath}: ${e.message}` })
57
+ }
58
+ child.once('error', (e) => resolve({ ok: false, blocked: false, message: `could not start ${execPath}: ${e.message}` }))
59
+ child.once('spawn', () => {
60
+ const exited = new Promise((r) => child.once('exit', (code, signal) => r(signal ?? code)))
61
+ child.unref()
62
+ resolve({ ok: true, pid: child.pid, exited })
63
+ })
64
+ })
65
+ }
66
+ const ps = windowsPowershell(how, env)
67
+ if (!ps) return { ok: false, blocked: true, message: wmiBlockedMessage('Windows PowerShell is not reachable from this WSL distro') }
68
+ let commandLine
69
+ try {
70
+ if (how === 'wmi') commandLine = [execPath, ...args].map(windowsArg).join(' ')
71
+ else {
72
+ const distro = wslDistro(env.WSL_DISTRO_NAME ?? '')
73
+ const user = wslUser(userInfo().username)
74
+ commandLine = ['wsl.exe', '-d', distro, '-u', user, '--cd', cwd, '--exec', execPath, ...args].map(windowsArg).join(' ')
75
+ }
76
+ } catch (e) {
77
+ return { ok: false, blocked: false, message: e.message }
78
+ }
79
+ const script = wmiScript({ commandLine, cwd: how === 'wmi' ? cwd : null })
80
+ const answer = await askPowershell(ps, script, env, parseWmiAnswer)
81
+ if (!answer.ok) return { ok: false, blocked: true, message: wmiBlockedMessage(answer.message) }
82
+ // A Windows pid can be watched from Windows; from inside WSL it names nothing here
83
+ /*
84
+ * Measured on a Windows 11 laptop (2026-10-08): a `wsl.exe` that WMI creates can hang without
85
+ * running anything in the distro (it starts a second wsl.exe and waits), while `wsl.exe --list`
86
+ * from the same context answers. `--detach` reports that as a start that never ran, and ends what
87
+ * it created rather than leave it waiting: this pid and its children, nothing else.
88
+ */
89
+ const taskkill = windowsTool(how, env, ['System32', 'taskkill.exe'])
90
+ const stop = taskkill ? () => runCaptured(taskkill, ['/PID', String(answer.pid), '/T', '/F'], env) : null
91
+ return { ok: true, pid: answer.pid, alive: how === 'wmi' ? () => isAlive(answer.pid) : null, stop }
92
+ }
93
+
94
+ /**
95
+ * `centralu serve --detach` (docs/plans/remote-hub.md §10.4, S9): starts `serve` outside this
96
+ * session (`detachHow`) and returns once its host answers a hello, so the caller, typically the
97
+ * hub over ssh, can connect at once.
98
+ *
99
+ * stdout carries one JSON line, read by the hub (`links/tunnel.ts`): the connection line with
100
+ * `hostRunning: true` and `detach: { ok: true, how, already }`, or `{ v: 1, detach: { ok: false,
101
+ * how, reason, message } }`. `reason` is `wmi_blocked` when WMI created nothing or created something
102
+ * that never ran, which the hub answers with a link-bound start; `exited` and `timeout` quote the
103
+ * end of serve.log. Exit codes do not survive Windows' ssh (agent-host.md §4.8), so the line is
104
+ * what counts; the exit code is 0 or 1 for a person at a prompt.
105
+ *
106
+ * `start` and the two waits are parameters so tests can stand in for WMI.
107
+ */
108
+ export async function runDetach({
109
+ env,
110
+ home,
111
+ entry,
112
+ version,
113
+ cliPath,
114
+ port = null,
115
+ from = null,
116
+ platform = process.platform,
117
+ execPath = process.execPath,
118
+ cwd = process.cwd(),
119
+ start = startDetached,
120
+ how = detachHow(platform, env),
121
+ signIn = startInSignIn,
122
+ signInMs = 20_000,
123
+ timeoutMs = 30_000,
124
+ noStartMs = 10_000,
125
+ write = (line) => process.stdout.write(line),
126
+ }) {
127
+ // Created here, so the token exists before the launcher reads it and `answered` reads it again
128
+ const { dataDir } = serveFolder({ env, home, cliPath, platform })
129
+ const fail = (reason, message) => answerLine(write, 'detach', { ok: false, how, reason, message })
130
+ const answered = async (already, as = how) => {
131
+ const d = await describe({ env, dataDir, state: ensureServeState(dataDir, platform), entry, version })
132
+ if (!d?.hostRunning) return false
133
+ write(`${connectionLine({ ...d, detach: { ok: true, how: as, already } })}\n`)
134
+ return true
135
+ }
136
+ if (await answered(true)) return 0
137
+
138
+ /*
139
+ * Windows: in the person's sign-in when someone is signed in (#1224), through the scheduled task, and through WMI only
140
+ * when nobody is. WMI's process keeps this ssh session's network logon, where Git cannot use the credentials saved in
141
+ * Windows. A task-started host that does not answer in time is left to the lock: the WMI start below then either
142
+ * holds the folder or is refused by it, never a second host on it.
143
+ */
144
+ if (how === 'wmi') {
145
+ const s = await signIn({ dataDir, env, home, platform })
146
+ if (s.started) {
147
+ say(`started centralu serve in the Windows sign-in (the scheduled task "${s.name}"); waiting for its host`)
148
+ const t0 = Date.now()
149
+ while (Date.now() - t0 < signInMs) {
150
+ if (await answered(false, 'task')) return 0
151
+ await sleep(250)
152
+ }
153
+ say(`the host the sign-in task started did not answer within ${Math.round(signInMs / 1000)} s; starting one through WMI instead`)
154
+ } else if (s.reason === 'nosession') {
155
+ say('nobody is signed in to Windows here: starting the host through WMI, outside any sign-in, where Git cannot use the credentials saved in Windows')
156
+ } else if (s.reason === 'error') {
157
+ say(`could not start the host in the Windows sign-in (${s.message}); starting it through WMI`)
158
+ }
159
+ }
160
+
161
+ const log = join(dataDir, SERVE_LOG_FILE)
162
+ // One start per log: the last one's is kept beside it, and its absence is how a start that never ran shows
163
+ try {
164
+ renameSync(log, `${log}.1`)
165
+ } catch {
166
+ // there was none
167
+ }
168
+ // Where this was asked for from (#1223): the launcher runs outside this ssh session, so it is told
169
+ const asked = serveFrom(env, from)
170
+ const childEnv = asked ? { ...env, CENTRALU_STARTED_FROM: JSON.stringify(asked) } : env
171
+ const args = [cliPath, 'serve', ...(port !== null ? ['--port', String(port)] : []), `${CHILD_FLAG}${encodeChildSpec({ env: childEnv, log })}`]
172
+ let started
173
+ try {
174
+ started = await start({ how, execPath, args, env, cwd })
175
+ } catch (e) {
176
+ return fail('failed', `could not start centralu serve in the background: ${e.message}`)
177
+ }
178
+ if (!started.ok) return fail(started.blocked ? 'wmi_blocked' : 'failed', started.message)
179
+ say(`started centralu serve in the background (${how}, pid ${started.pid ?? 'unknown'}); waiting for its host`)
180
+
181
+ let exited
182
+ started.exited?.then((c) => (exited = c ?? 'unknown'))
183
+ const t0 = Date.now()
184
+ while (Date.now() - t0 < timeoutMs) {
185
+ if (await answered(false)) return 0
186
+ const why = tail(log)
187
+ if (exited !== undefined) return fail('exited', `centralu serve exited (${exited}) before its host answered${why ? `:\n${why}` : ''}`)
188
+ const gone = started.alive?.() === false
189
+ if (how !== 'setsid' && !existsSync(log) && (gone || Date.now() - t0 > noStartMs)) {
190
+ // WMI said yes, and nothing ran: the process was stopped before Node started, or hangs (`startDetached`)
191
+ if (!gone) await started.stop?.()
192
+ return fail('wmi_blocked', wmiBlockedMessage(gone ? `process ${started.pid} ended before it started` : `nothing started within ${Math.round(noStartMs / 1000)} s`))
193
+ }
194
+ if (gone) return fail('exited', `centralu serve exited before its host answered${why ? `:\n${why}` : ''}`)
195
+ await sleep(250)
196
+ }
197
+ const why = tail(log)
198
+ return fail('timeout', `the host did not answer within ${Math.round(timeoutMs / 1000)} s${why ? `:\n${why}` : ''}`)
199
+ }
200
+
201
+ /**
202
+ * The launcher `--detach` started: `runServe` writing to serve.log. The carried variables are
203
+ * already in `env` (centralu.mjs merges them before it looks for the host).
204
+ */
205
+ export async function runDetachedChild({ spec, ...opts }) {
206
+ let fd = null
207
+ try {
208
+ fd = openSync(spec.log, 'a')
209
+ sayTo((text) => {
210
+ try {
211
+ writeSync(fd, text)
212
+ } catch {
213
+ // nowhere left to say it
214
+ }
215
+ })
216
+ } catch {
217
+ // no log: say() keeps stderr, which nobody reads; --detach then reports the start as never run
218
+ }
219
+ say(`started in the background (pid ${process.pid}, Node ${process.version})`)
220
+ try {
221
+ return await runServe({ ...opts, logFd: fd })
222
+ } catch (e) {
223
+ say(e?.message ?? String(e))
224
+ return 1
225
+ }
226
+ }
227
+
228
+ /**
229
+ * `centralu serve --stop` (docs/plans/remote-hub.md §10.4, S10): the running host stopped in order, over its own
230
+ * socket, and waited for (`stopServedHost` in serve-handover.mjs, which the hand-over into the sign-in shares, #1224).
231
+ *
232
+ * stdout: one line, `{ v: 1, stop: { ok, wasRunning, how?, message? } }`.
233
+ */
234
+ export async function runStop({
235
+ env,
236
+ home,
237
+ entry,
238
+ platform = process.platform,
239
+ timeoutMs = 30_000,
240
+ graceMs = 15_000,
241
+ kill = (pid, sig) => process.kill(pid, sig),
242
+ write = (line) => process.stdout.write(line),
243
+ }) {
244
+ const dataDir = serveDataDir(env, home)
245
+ return answerLine(write, 'stop', await stopServedHost({ dataDir, entry, platform, timeoutMs, graceMs, kill }))
246
+ }
@@ -0,0 +1,232 @@
1
+ /**
2
+ * The files `centralu serve` keeps in the data folder: the token and port (serve.json, private to the
3
+ * user), the running launcher's pid (serve.pid), and the host's own lock (host.lock), read to tell a
4
+ * live host of this folder from a stale pid.
5
+ */
6
+ import { execFileSync } from 'node:child_process'
7
+ import { randomBytes } from 'node:crypto'
8
+ import { chmodSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeSync, closeSync } from 'node:fs'
9
+ import { join } from 'node:path'
10
+ import { isAlive, replaceFile, sleepSync } from './serve-util.mjs'
11
+
12
+ /**
13
+ * The file in the data folder that holds the token and the port, mode 0600.
14
+ *
15
+ * The token is generated once, the first time either `serve` or `serve --connection` runs, and kept:
16
+ * the client stores it (in the OS secret store) and has to find the same one after the host
17
+ * restarts. The port is the one the last `serve` actually listened on, which is how
18
+ * `--connection`, a separate process, learns a `--port` given to `serve` in a systemd unit.
19
+ */
20
+ export const SERVE_STATE_FILE = 'serve.json'
21
+
22
+ /** What a detached serve writes: its own lines, and the host's until it is ready (host.log has the rest) */
23
+ export const SERVE_LOG_FILE = 'serve.log'
24
+
25
+ /** The running launcher's pid and port, so `--stop` can find it. Removed when it exits */
26
+ export const SERVE_PID_FILE = 'serve.pid'
27
+
28
+ /** The data folder: the host's own rule (`dataRoot()` in agent-host), CC_DATA_DIR or ~/.centralu */
29
+ export function serveDataDir(env, home) {
30
+ return env.CC_DATA_DIR || join(home, '.centralu')
31
+ }
32
+
33
+ /**
34
+ * The state, or null when there is none yet or it cannot be read as one. A file that is refused (Windows, while a
35
+ * writer or a scanner has it) or does not parse is read again a few times before it counts as unreadable: a
36
+ * `--detach` waiting for the port reads it while the launcher replaces it (#1041).
37
+ */
38
+ export function readServeState(dataDir, { tries = 5, sleep = sleepSync } = {}) {
39
+ const file = join(dataDir, SERVE_STATE_FILE)
40
+ for (let i = 1; ; i++) {
41
+ let raw
42
+ try {
43
+ raw = readFileSync(file, 'utf8')
44
+ } catch (e) {
45
+ if (e?.code === 'ENOENT' || i >= tries) return null
46
+ sleep(10 * i)
47
+ continue
48
+ }
49
+ const state = parseServeState(raw)
50
+ if (state || i >= tries) return state
51
+ sleep(10 * i)
52
+ }
53
+ }
54
+
55
+ function parseServeState(raw) {
56
+ try {
57
+ const v = JSON.parse(raw)
58
+ if (typeof v?.token !== 'string' || v.token.length < 32) return null
59
+ return { token: v.token, port: Number.isInteger(v.port) && v.port >= 1 && v.port <= 65535 ? v.port : null }
60
+ } catch {
61
+ return null
62
+ }
63
+ }
64
+
65
+ /**
66
+ * The state, created on first use. Never replaces a token that is already there.
67
+ *
68
+ * Created with `wx`, so two first runs at the same moment (a `serve` and a `--connection`) cannot
69
+ * each write a different token: the second one fails to create and reads the first one's. A file
70
+ * that exists but cannot be read as state is refused rather than overwritten: it may be a token
71
+ * the client already holds, and a silent new one would lock that client out with "bad token".
72
+ */
73
+ export function ensureServeState(dataDir, platform = process.platform) {
74
+ mkdirSync(dataDir, { recursive: true })
75
+ const file = join(dataDir, SERVE_STATE_FILE)
76
+ if (!existsSync(file)) {
77
+ const token = randomBytes(32).toString('base64url')
78
+ try {
79
+ writePrivate(file, { v: 1, token, port: null }, 'wx')
80
+ } catch (e) {
81
+ if (e?.code !== 'EEXIST') throw e
82
+ }
83
+ }
84
+ const state = readServeState(dataDir)
85
+ if (!state) throw new Error(`${file} exists but is not a serve state file. Move it aside and run again.`)
86
+ keepPrivate(file, platform)
87
+ return state
88
+ }
89
+
90
+ /** Writes the port `serve` listened on, keeping the token. Atomic: a temp file renamed over it */
91
+ export function recordServePort(dataDir, port, platform = process.platform) {
92
+ const file = join(dataDir, SERVE_STATE_FILE)
93
+ const state = readServeState(dataDir)
94
+ if (!state) throw new Error(`${file} is missing or unreadable`)
95
+ if (state.port === port) return
96
+ replacePrivate(file, { v: 1, token: state.token, port }, platform)
97
+ }
98
+
99
+ /**
100
+ * A new token, keeping the port. Only when the person asks (`--rotate-token`): every client that
101
+ * stored the old one has to fetch the new one with `--connection`, and a serve already running
102
+ * keeps answering to the old one until it restarts.
103
+ */
104
+ export function rotateServeToken(dataDir, platform = process.platform) {
105
+ const before = ensureServeState(dataDir, platform)
106
+ replacePrivate(join(dataDir, SERVE_STATE_FILE), { v: 1, token: randomBytes(32).toString('base64url'), port: before.port }, platform)
107
+ return readServeState(dataDir)
108
+ }
109
+
110
+ /**
111
+ * Created 0600 from the first byte, not chmod-ed after: a file written with the default mode and
112
+ * narrowed afterwards is readable by everyone on the machine for the moment in between.
113
+ */
114
+ function writePrivate(file, value, flag) {
115
+ const fd = openSync(file, flag, 0o600)
116
+ try {
117
+ writeSync(fd, `${JSON.stringify(value)}\n`)
118
+ } finally {
119
+ closeSync(fd)
120
+ }
121
+ }
122
+
123
+ /** Replaces a private file whole (`replaceFile`), created 0600 as `writePrivate` creates one */
124
+ function replacePrivate(file, value, platform) {
125
+ replaceFile(file, `${JSON.stringify(value)}\n`, { mode: 0o600, flag: 'wx' })
126
+ keepPrivate(file, platform)
127
+ }
128
+
129
+ /**
130
+ * 0600 again on every use. A copy, a restore from backup or an editor that rewrites the file can
131
+ * leave it readable by the group; the token in it is the key to every RPC. Windows has no mode
132
+ * bits to set (the profile folder's ACL is what protects it there).
133
+ */
134
+ function keepPrivate(file, platform) {
135
+ if (platform === 'win32') return
136
+ if ((statSync(file).mode & 0o777) !== 0o600) chmodSync(file, 0o600)
137
+ }
138
+
139
+ /** serve.pid: `{ pid, hostPid, port }` of the launcher that runs, or null */
140
+ export function readServePid(dataDir) {
141
+ try {
142
+ const v = JSON.parse(readFileSync(join(dataDir, SERVE_PID_FILE), 'utf8'))
143
+ return Number.isInteger(v?.pid) && v.pid > 0 ? { pid: v.pid, hostPid: Number.isInteger(v.hostPid) ? v.hostPid : null, port: v.port ?? null } : null
144
+ } catch {
145
+ return null
146
+ }
147
+ }
148
+
149
+ export function removeServePid(dataDir, pid) {
150
+ if (readServePid(dataDir)?.pid !== pid) return
151
+ try {
152
+ rmSync(join(dataDir, SERVE_PID_FILE), { force: true })
153
+ } catch {
154
+ // another serve's by now, or gone
155
+ }
156
+ }
157
+
158
+ /**
159
+ * A probe that did not prove the token, while this data folder's host is alive (`host.lock`): a host from before #838
160
+ * still running after an update. It is running, and is not sent the token; a hub asking it for a proof is refused
161
+ * until it restarts. Without a live lock holder, what answered is not ours.
162
+ */
163
+ export function heldHere(probe, dataDir, startOf = processStartTime) {
164
+ if (probe.running) return true
165
+ if (!probe.unproven) return false
166
+ return lockHolderIsAlive(dataDir, startOf)
167
+ }
168
+
169
+ /**
170
+ * Whether the process `host.lock` names is the one that wrote it (#838 review): alive, and started when the lock says
171
+ * (`ps -o lstart`, as the host writes it, `instance-lock.ts`). A lock left by a host that died, whose pid another
172
+ * process of the same user now has, names a stranger: counted as running, `--stop` would signal it. A lock without a
173
+ * start time (a host from before #184) or a system without `ps` (Windows) cannot be told apart, so it does not count.
174
+ */
175
+ export function lockHolderIsAlive(dataDir, startOf = processStartTime) {
176
+ let holder
177
+ try {
178
+ holder = parseLockHolder(readFileSync(join(dataDir, 'host.lock'), 'utf8'))
179
+ } catch {
180
+ return false
181
+ }
182
+ if (!holder || !holder.started || !isAlive(holder.pid)) return false
183
+ return startOf(holder.pid) === holder.started
184
+ }
185
+
186
+ /**
187
+ * host.lock's `{ pid, started, by? }`; a bare pid (an older host) has no start time. `by` (#1223, additive) is who
188
+ * started the host: `app`, `keeper` or `serve` (`instance-lock.ts`), absent when the host did not say
189
+ */
190
+ function parseLockHolder(text) {
191
+ const t = text.trim()
192
+ if (/^\d+$/.test(t)) return Number(t) > 0 ? { pid: Number(t), started: null } : null
193
+ try {
194
+ const v = JSON.parse(t)
195
+ if (!Number.isInteger(v?.pid) || v.pid <= 0) return null
196
+ const by = v.by === 'app' || v.by === 'keeper' || v.by === 'serve' ? v.by : null
197
+ return { pid: v.pid, started: typeof v.started === 'string' ? v.started : null, ...(by ? { by } : {}) }
198
+ } catch {
199
+ return null
200
+ }
201
+ }
202
+
203
+ /**
204
+ * A pid's start time, as `instance-lock.ts`'s `processStartTime` reads it: `ps -o lstart=` with the C locale, so the
205
+ * host that wrote the lock and this launcher read the same text. null without `ps` (Windows) or when it fails.
206
+ */
207
+ export function processStartTime(pid) {
208
+ if (process.platform === 'win32') return null
209
+ try {
210
+ return execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], { encoding: 'utf8', timeout: 2000, env: { ...process.env, LC_ALL: 'C' }, stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null
211
+ } catch {
212
+ return null
213
+ }
214
+ }
215
+
216
+ /** Who `host.lock` names as the data folder's owner, `{ pid, started, by? }`, or null */
217
+ export function lockHolder(dataDir) {
218
+ try {
219
+ return parseLockHolder(readFileSync(join(dataDir, 'host.lock'), 'utf8'))
220
+ } catch {
221
+ return null
222
+ }
223
+ }
224
+
225
+ /** Who `host.lock` names as the data folder's owner, or null */
226
+ export function lockHolderPid(dataDir) {
227
+ try {
228
+ return parseLockHolder(readFileSync(join(dataDir, 'host.lock'), 'utf8'))?.pid ?? null
229
+ } catch {
230
+ return null
231
+ }
232
+ }
@@ -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
+ }