conductor-remote 1.8.0 → 1.9.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.
@@ -1,485 +0,0 @@
1
- /**
2
- * Deploy the relay as a macOS LaunchAgent — the only "deployment" this app has, since it must run
3
- * on the Mac that runs Conductor (local SQLite DB, git worktrees, and the sidecar unix socket all
4
- * live there). Installs a per-user agent that starts the relay on login and keeps it alive.
5
- *
6
- * node scripts/service.ts <install|uninstall|status|restart>
7
- * (or, once installed globally: `conductor-remote service <...>`)
8
- *
9
- * `yarn deploy` builds dist/ first, then runs `install`.
10
- */
11
- import { execFileSync } from 'node:child_process'
12
- import fs from 'node:fs'
13
- import os from 'node:os'
14
- import path from 'node:path'
15
- import { qrLines } from './qr.ts'
16
-
17
- const LABEL = 'no.adluna.conductor-remote'
18
- const projectDir = path.resolve(import.meta.dirname, '..')
19
- const plistPath = path.join(os.homedir(), 'Library', 'LaunchAgents', `${LABEL}.plist`)
20
- const logDir = path.join(os.homedir(), 'Library', 'Logs', 'conductor-remote')
21
- const uid = process.getuid?.() ?? 0
22
- const domain = `gui/${uid}`
23
-
24
- /**
25
- * Install-time knobs are accepted as documented CLI flags OR the matching env var — a flag wins over the
26
- * ambient env. Parsed flags are folded back into process.env so everything downstream (and the plist we
27
- * bake) keeps reading a single source. Runs before any module-level env read below.
28
- */
29
- const FLAG_ENV: Record<string, string> = {
30
- '--expose': 'EXPOSE',
31
- '--port': 'RELAY_PORT',
32
- '--host': 'RELAY_HOST',
33
- '--token': 'RELAY_TOKEN',
34
- '--write-strategy': 'WRITE_STRATEGY',
35
- '--auto-update': 'AUTO_UPDATE',
36
- '--db': 'CONDUCTOR_DB',
37
- '--workspaces': 'CONDUCTOR_WORKSPACES'
38
- }
39
-
40
- function applyFlags(argv: string[]): void {
41
- for (let i = 0; i < argv.length; i++) {
42
- const arg = argv[i]
43
- if (!arg.startsWith('--')) continue
44
- const eq = arg.indexOf('=')
45
- const name = eq === -1 ? arg : arg.slice(0, eq)
46
- const envKey = FLAG_ENV[name]
47
- if (!envKey) {
48
- console.error(`unknown flag: ${name}\n known: ${Object.keys(FLAG_ENV).join(', ')}`)
49
- process.exit(1)
50
- }
51
- const value = eq === -1 ? argv[++i] : arg.slice(eq + 1)
52
- if (value === undefined) {
53
- console.error(`flag ${name} needs a value (e.g. ${name} <value>)`)
54
- process.exit(1)
55
- }
56
- process.env[envKey] = value
57
- }
58
- }
59
-
60
- // argv[2] is the subcommand (see bottom); flags follow it.
61
- applyFlags(process.argv.slice(3))
62
-
63
- function xml(s: string): string {
64
- return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
65
- }
66
-
67
- /** Run launchctl, swallowing the exit code so "already-loaded"/"not-loaded" states aren't fatal. */
68
- function launchctl(...args: string[]): void {
69
- try {
70
- execFileSync('launchctl', args, { stdio: 'pipe' })
71
- } catch {
72
- // non-zero is expected for bootout-when-absent etc.; state is asserted by the caller's sequence
73
- }
74
- }
75
-
76
- /** Block the main thread briefly — used to let launchd settle between bootout and bootstrap. */
77
- function sleepSync(ms: number): void {
78
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
79
- }
80
-
81
- /** Is the agent currently bootstrapped into the user domain? */
82
- function serviceLoaded(): boolean {
83
- try {
84
- execFileSync('launchctl', ['print', `${domain}/${LABEL}`], { stdio: 'pipe' })
85
- return true
86
- } catch {
87
- return false
88
- }
89
- }
90
-
91
- /**
92
- * Reload the agent from the freshly written plist. `bootout` of a *running* instance is asynchronous,
93
- * so we wait for it to fully unload before `bootstrap` — otherwise bootstrap races the teardown and
94
- * fails silently, leaving the relay down after a re-deploy. Bootstrap is retried and its failure is fatal.
95
- */
96
- function reloadAgent(): void {
97
- launchctl('bootout', `${domain}/${LABEL}`)
98
- for (let i = 0; i < 30 && serviceLoaded(); i++) sleepSync(100)
99
- let bootstrapped = false
100
- for (let i = 0; i < 10 && !bootstrapped; i++) {
101
- try {
102
- execFileSync('launchctl', ['bootstrap', domain, plistPath], { stdio: 'pipe' })
103
- bootstrapped = true
104
- } catch {
105
- sleepSync(150)
106
- }
107
- }
108
- if (!bootstrapped) {
109
- console.error(`✗ launchctl bootstrap failed for ${plistPath}`)
110
- console.error(` Inspect with: launchctl print ${domain}/${LABEL}`)
111
- process.exit(1)
112
- }
113
- launchctl('enable', `${domain}/${LABEL}`)
114
- launchctl('kickstart', '-k', `${domain}/${LABEL}`)
115
- }
116
-
117
- /** Node runs the relay via the flag-free CLI shim; the absolute execPath is baked at install time. */
118
- function buildPlist(): string {
119
- const node = xml(process.execPath)
120
- const proj = xml(projectDir)
121
- const out = xml(path.join(logDir, 'relay.log'))
122
- const err = xml(path.join(logDir, 'relay.err.log'))
123
- // node's own dir leads so the daemon can find `npm` (adjacent to node) for self-update under launchd's
124
- // bare PATH; Homebrew's bin is appended for tailscale/node on Apple Silicon.
125
- const nodeDir = path.dirname(process.execPath)
126
- const daemonPath = `${nodeDir}:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/homebrew/bin`
127
- // MANAGED marks this as the launchd-supervised instance: autoupdate.ts only self-restarts (exit →
128
- // KeepAlive respawn) when it sees this, so a dev `yarn start` or worktree run never auto-updates.
129
- const envEntries: Array<[string, string]> = [
130
- ['PATH', daemonPath],
131
- ['CONDUCTOR_REMOTE_MANAGED', '1']
132
- ]
133
- if (process.env.WRITE_STRATEGY) envEntries.push(['WRITE_STRATEGY', process.env.WRITE_STRATEGY])
134
- if (process.env.RELAY_HOST) envEntries.push(['RELAY_HOST', process.env.RELAY_HOST])
135
- if (process.env.RELAY_PORT) envEntries.push(['RELAY_PORT', process.env.RELAY_PORT])
136
- if (process.env.AUTO_UPDATE) envEntries.push(['AUTO_UPDATE', process.env.AUTO_UPDATE])
137
- if (process.env.CONDUCTOR_DB) envEntries.push(['CONDUCTOR_DB', process.env.CONDUCTOR_DB])
138
- if (process.env.CONDUCTOR_WORKSPACES) envEntries.push(['CONDUCTOR_WORKSPACES', process.env.CONDUCTOR_WORKSPACES])
139
- const envXml = envEntries.map(([k, v]) => `\t\t<key>${xml(k)}</key>\n\t\t<string>${xml(v)}</string>`).join('\n')
140
- return `<?xml version="1.0" encoding="UTF-8"?>
141
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
142
- <plist version="1.0">
143
- <dict>
144
- <key>Label</key>
145
- <string>${LABEL}</string>
146
- <key>ProgramArguments</key>
147
- <array>
148
- <string>${node}</string>
149
- <string>${proj}/bin/cli.js</string>
150
- </array>
151
- <key>WorkingDirectory</key>
152
- <string>${proj}</string>
153
- <key>EnvironmentVariables</key>
154
- <dict>
155
- ${envXml}
156
- </dict>
157
- <key>RunAtLoad</key>
158
- <true/>
159
- <key>KeepAlive</key>
160
- <true/>
161
- <key>ProcessType</key>
162
- <string>Background</string>
163
- <key>StandardOutPath</key>
164
- <string>${out}</string>
165
- <key>StandardErrorPath</key>
166
- <string>${err}</string>
167
- </dict>
168
- </plist>
169
- `
170
- }
171
-
172
- function distBuilt(): boolean {
173
- return fs.existsSync(path.join(projectDir, 'dist', 'index.html'))
174
- }
175
-
176
- function tokenStorePath(): string {
177
- return path.join(os.homedir(), 'Library', 'Application Support', 'conductor-remote', 'token')
178
- }
179
-
180
- /** Read the persisted token (or env override) purely to print the phone URL — never mints one. */
181
- function currentToken(): string | null {
182
- if (process.env.RELAY_TOKEN) return process.env.RELAY_TOKEN
183
- try {
184
- return fs.readFileSync(tokenStorePath(), 'utf8').trim() || null
185
- } catch {
186
- return null
187
- }
188
- }
189
-
190
- /**
191
- * A pinned token (`--token` / `RELAY_TOKEN`) is persisted to the token file, not baked into the plist —
192
- * the launchd daemon has no such env, so it resolves the secret from this file (config.ts ▸ resolveToken).
193
- * Writing it here keeps the daemon, the printed URL, and later `status` all in agreement.
194
- */
195
- function persistPinnedToken(): void {
196
- const token = process.env.RELAY_TOKEN
197
- if (!token) return
198
- try {
199
- fs.mkdirSync(path.dirname(tokenStorePath()), { recursive: true })
200
- fs.writeFileSync(tokenStorePath(), token, { mode: 0o600 })
201
- } catch (err) {
202
- console.info(` ⚠ could not persist --token (${err instanceof Error ? err.message : err})`)
203
- }
204
- }
205
-
206
- const RELAY_PORT = process.env.RELAY_PORT ?? '8787'
207
-
208
- /** Locate the tailscale CLI: PATH first, then the common macOS install locations. Null if absent. */
209
- function tailscaleBin(): string | null {
210
- for (const bin of [
211
- 'tailscale',
212
- '/opt/homebrew/bin/tailscale',
213
- '/usr/local/bin/tailscale',
214
- '/Applications/Tailscale.app/Contents/MacOS/Tailscale'
215
- ]) {
216
- try {
217
- execFileSync(bin, ['version'], { stdio: 'pipe' })
218
- return bin
219
- } catch {
220
- // try the next candidate
221
- }
222
- }
223
- return null
224
- }
225
-
226
- /** This node's MagicDNS name without the trailing dot, e.g. `mac.taila6dcd6.ts.net`. */
227
- function magicDnsName(bin: string): string | null {
228
- try {
229
- const out = execFileSync(bin, ['status', '--json'], { encoding: 'utf8', stdio: 'pipe' })
230
- return (JSON.parse(out)?.Self?.DNSName ?? '').replace(/\.$/, '') || null
231
- } catch {
232
- return null
233
- }
234
- }
235
-
236
- /**
237
- * How the stable HTTPS URL is fronted:
238
- * 'public' → `tailscale funnel` — reachable from ANY browser on the internet (token-gated).
239
- * 'tailnet' → `tailscale serve` — reachable only by devices logged into this tailnet.
240
- */
241
- type ExposeMode = 'public' | 'tailnet'
242
-
243
- /** Where the chosen expose mode is persisted so a later bare `yarn deploy` keeps the same posture. */
244
- function exposeStorePath(): string {
245
- return path.join(os.homedir(), 'Library', 'Application Support', 'conductor-remote', 'expose')
246
- }
247
-
248
- function normalizeMode(raw: string | undefined): ExposeMode | null {
249
- const v = raw?.trim().toLowerCase()
250
- if (v === 'public' || v === 'funnel') return 'public'
251
- if (v === 'tailnet' || v === 'serve' || v === 'private') return 'tailnet'
252
- return null
253
- }
254
-
255
- /**
256
- * Resolve the expose mode. Precedence: `EXPOSE` env (public|funnel / tailnet|serve|private) > persisted
257
- * choice > 'public' default. An explicit env value is persisted so re-deploys don't silently flip posture.
258
- */
259
- function resolveExposeMode(): ExposeMode {
260
- const fromEnv = normalizeMode(process.env.EXPOSE)
261
- if (fromEnv) {
262
- try {
263
- const file = exposeStorePath()
264
- fs.mkdirSync(path.dirname(file), { recursive: true })
265
- fs.writeFileSync(file, fromEnv)
266
- } catch {
267
- // persistence is a convenience; ignore failures
268
- }
269
- return fromEnv
270
- }
271
- if (process.env.EXPOSE) console.info(` ⚠ unrecognized EXPOSE=${process.env.EXPOSE} — expected public|tailnet.`)
272
- try {
273
- const saved = normalizeMode(fs.readFileSync(exposeStorePath(), 'utf8'))
274
- if (saved) return saved
275
- } catch {
276
- // no saved choice yet
277
- }
278
- return 'public'
279
- }
280
-
281
- /** Live serve/funnel state for this node: is the loopback proxy wired, and is Funnel (public) on? */
282
- function tailscaleState(bin: string, dns: string | null): { proxyOk: boolean; funnelOn: boolean } {
283
- if (!dns) return { proxyOk: false, funnelOn: false }
284
- try {
285
- const out = execFileSync(bin, ['serve', 'status', '--json'], { encoding: 'utf8', stdio: 'pipe' })
286
- const cfg = JSON.parse(out)
287
- const key = `${dns}:443`
288
- const proxyOk = cfg?.Web?.[key]?.Handlers?.['/']?.Proxy === `http://127.0.0.1:${RELAY_PORT}`
289
- return { proxyOk, funnelOn: Boolean(cfg?.AllowFunnel?.[key]) }
290
- } catch {
291
- return { proxyOk: false, funnelOn: false }
292
- }
293
- }
294
-
295
- /** Assert the tailnet-only `serve` proxy — used for tailnet mode and as the Funnel fallback. */
296
- function ensureServeOnly(bin: string, url: string, state: { proxyOk: boolean; funnelOn: boolean }): void {
297
- if (state.proxyOk && !state.funnelOn) {
298
- console.info(`✓ tailscale serve fronts ${url} → 127.0.0.1:${RELAY_PORT} (tailnet-only)`)
299
- return
300
- }
301
- try {
302
- execFileSync(bin, ['serve', '--bg', RELAY_PORT], { stdio: 'pipe' })
303
- console.info(`✓ tailscale serve → ${url} proxies 127.0.0.1:${RELAY_PORT} (tailnet-only)`)
304
- } catch (err) {
305
- console.info(
306
- `\n ⚠ could not configure tailscale serve (${err instanceof Error ? err.message : err}). Run by hand:`
307
- )
308
- console.info(` tailscale serve --bg ${RELAY_PORT}`)
309
- }
310
- }
311
-
312
- /**
313
- * Front the loopback relay with a stable HTTPS URL, either publicly (`tailscale funnel`, the default) or
314
- * tailnet-only (`tailscale serve`), per resolveExposeMode(). Idempotent — flips Funnel off when switching
315
- * back to tailnet — and non-fatal: the relay binds loopback regardless, so a failure here just means the
316
- * phone URL isn't wired yet and we print how to do it by hand. Real TLS also satisfies the PWA's
317
- * secure-context requirement (a service worker won't register over plain http on a 100.x IP).
318
- *
319
- * PUBLIC IS INTERNET-FACING: the 128-bit token on every /api/* request is the only gate. Funnel must be
320
- * enabled for the tailnet (Admin console) or the funnel command fails — we then fall back to tailnet-only.
321
- */
322
- function ensureTailscale(): void {
323
- const bin = tailscaleBin()
324
- if (!bin) {
325
- console.info('\n ⚠ tailscale CLI not found — skipped URL setup. Once Tailscale is installed, run:')
326
- console.info(` tailscale funnel --bg ${RELAY_PORT} # public, or \`serve\` for tailnet-only`)
327
- return
328
- }
329
- const dns = magicDnsName(bin)
330
- const url = `https://${dns ?? '<node>'}/`
331
- const mode = resolveExposeMode()
332
- const state = tailscaleState(bin, dns)
333
-
334
- if (mode === 'tailnet') {
335
- if (state.funnelOn) {
336
- try {
337
- execFileSync(bin, ['funnel', 'reset'], { stdio: 'pipe' })
338
- } catch {
339
- // best-effort; ensureServeOnly re-asserts the proxy below
340
- }
341
- ensureServeOnly(bin, url, { proxyOk: false, funnelOn: false })
342
- } else {
343
- ensureServeOnly(bin, url, state)
344
- }
345
- return
346
- }
347
-
348
- // public (Funnel)
349
- if (state.proxyOk && state.funnelOn) {
350
- console.info(`✓ tailscale funnel already exposes ${url} → 127.0.0.1:${RELAY_PORT} (public, token-gated)`)
351
- return
352
- }
353
- try {
354
- execFileSync(bin, ['funnel', '--bg', '--yes', RELAY_PORT], { stdio: 'pipe' })
355
- console.info(`✓ tailscale funnel → ${url} now public over the internet (token-gated) → 127.0.0.1:${RELAY_PORT}`)
356
- } catch (err) {
357
- console.info(`\n ⚠ could not enable Funnel (${err instanceof Error ? err.message.trim() : err}).`)
358
- console.info(' Funnel must be enabled for this tailnet: open the URL Tailscale printed above, or add the')
359
- console.info(' "funnel" nodeAttr in Admin console ▸ Access controls. Falling back to tailnet-only for now.')
360
- ensureServeOnly(bin, url, state)
361
- }
362
- }
363
-
364
- /** Print a scannable QR of `url` (theme-independent black-on-white). Never fatal — QR is a convenience. */
365
- function printQr(url: string): void {
366
- try {
367
- console.info(`\n${qrLines(url).join('\n')}`)
368
- } catch (err) {
369
- console.info(` (QR skipped: ${err instanceof Error ? err.message : err})`)
370
- }
371
- }
372
-
373
- function printUrl(): void {
374
- const token = currentToken()
375
- const frag = `#token=${token ?? '<starts on first run>'}`
376
- const bin = tailscaleBin()
377
- const dns = bin ? magicDnsName(bin) : null
378
- const state = bin ? tailscaleState(bin, dns) : { proxyOk: false, funnelOn: false }
379
- if (dns && state.proxyOk) {
380
- const scope = state.funnelOn ? 'public — any browser, token-gated' : 'same Tailnet only'
381
- const url = `https://${dns}/${frag}`
382
- console.info(`\n Phone URL (HTTPS, ${scope}):\n ${url}`)
383
- if (token) {
384
- console.info('\n Scan to open on your phone:')
385
- printQr(url)
386
- }
387
- return
388
- }
389
- // Nothing fronting yet — the relay is only on loopback.
390
- console.info(`\n Local URL:\n http://127.0.0.1:${RELAY_PORT}/${frag}`)
391
- console.info(
392
- `\n ⚠ Not reachable from your phone yet. Run \`tailscale funnel --bg ${RELAY_PORT}\` (public) or \`tailscale serve --bg ${RELAY_PORT}\` (tailnet)${dns ? ` → https://${dns}/` : ''}, then \`yarn service status\`.`
393
- )
394
- }
395
-
396
- /** npx unpacks into a throwaway cache that gets purged; a LaunchAgent baked against it would rot. */
397
- function isEphemeralInstall(dir: string): boolean {
398
- return /[\\/]_npx[\\/]|[\\/]\.npm[\\/]_npx[\\/]/.test(dir)
399
- }
400
-
401
- function install(): void {
402
- if (isEphemeralInstall(projectDir)) {
403
- console.error(
404
- `✗ refusing to install from an npx cache path:\n ${projectDir}\n` +
405
- ' That directory is temporary and gets purged, which would break the LaunchAgent.\n' +
406
- ' Install globally first: `npm i -g conductor-remote`, then `conductor-remote service install`.'
407
- )
408
- process.exit(1)
409
- }
410
- if (!distBuilt()) {
411
- console.error('✗ dist/ not built. Run `yarn build` first (or use `yarn deploy`, which builds).')
412
- process.exit(1)
413
- }
414
- persistPinnedToken()
415
- fs.mkdirSync(path.dirname(plistPath), { recursive: true })
416
- fs.mkdirSync(logDir, { recursive: true })
417
- fs.writeFileSync(plistPath, buildPlist())
418
- reloadAgent()
419
- console.info(`✓ installed LaunchAgent ${LABEL}`)
420
- console.info(` plist: ${plistPath}`)
421
- console.info(` logs: ${logDir}/relay.log`)
422
- console.info(` node: ${process.execPath}`)
423
- ensureTailscale()
424
- printUrl()
425
- console.info(
426
- '\n Note: a node version change (nvm) invalidates the baked path — re-run `yarn deploy` after upgrading node.'
427
- )
428
- console.info(
429
- ' Note: the AppleScript write path needs Accessibility permission granted to this node binary (System Settings ▸ Privacy).'
430
- )
431
- }
432
-
433
- function uninstall(): void {
434
- launchctl('bootout', `${domain}/${LABEL}`)
435
- try {
436
- fs.rmSync(plistPath)
437
- } catch {
438
- // already gone
439
- }
440
- console.info(`✓ removed LaunchAgent ${LABEL}`)
441
- }
442
-
443
- function restart(): void {
444
- launchctl('kickstart', '-k', `${domain}/${LABEL}`)
445
- console.info(`✓ restarted ${LABEL}`)
446
- printUrl()
447
- }
448
-
449
- function status(): void {
450
- const installed = fs.existsSync(plistPath)
451
- console.info(`plist: ${installed ? plistPath : '(not installed)'}`)
452
- if (!installed) return
453
- try {
454
- const out = execFileSync('launchctl', ['print', `${domain}/${LABEL}`], { encoding: 'utf8', stdio: 'pipe' })
455
- const state = out.match(/state = (\S+)/)?.[1] ?? 'unknown'
456
- const pid = out.match(/pid = (\d+)/)?.[1] ?? '—'
457
- console.info(`state: ${state} (pid ${pid})`)
458
- } catch {
459
- console.info('state: loaded but not running (check logs)')
460
- }
461
- printUrl()
462
- }
463
-
464
- const cmd = process.argv[2] ?? 'status'
465
- switch (cmd) {
466
- case 'install':
467
- install()
468
- break
469
- case 'uninstall':
470
- uninstall()
471
- break
472
- case 'restart':
473
- restart()
474
- break
475
- case 'status':
476
- status()
477
- break
478
- default:
479
- console.error(
480
- `unknown command: ${cmd}\n` +
481
- 'usage: service.ts <install|uninstall|restart|status> [flags]\n' +
482
- ` flags (install): ${Object.keys(FLAG_ENV).join(', ')}`
483
- )
484
- process.exit(1)
485
- }
package/src/autoupdate.ts DELETED
@@ -1,179 +0,0 @@
1
- /**
2
- * Self-update for the globally-installed relay daemon.
3
- *
4
- * The relay ships as a global npm package driven by a KeepAlive LaunchAgent. Without this, staying
5
- * current means the user manually re-running `npm i -g conductor-remote && conductor-remote service
6
- * install`. Here the running daemon periodically asks the npm registry for the latest published
7
- * version and, when it's newer, runs `npm i -g conductor-remote@latest` and exits — launchd's
8
- * KeepAlive restarts it into the freshly-installed code (the plist's baked `bin/cli.js` path is stable
9
- * across a global reinstall, so no re-`service install` is needed).
10
- *
11
- * Two hard gates keep this from firing where it shouldn't:
12
- * - CONDUCTOR_REMOTE_MANAGED=1 — set only by `service install` in the plist, so it proves we are the
13
- * launchd-managed daemon and that exit()→KeepAlive-restart is a safe way to reload.
14
- * - projectDir has no `.git` — proves we're the published tarball, not a dev worktree. A worktree's
15
- * LaunchAgent runs from the worktree path, so `npm i -g` wouldn't even swap its code; never touch it.
16
- *
17
- * `AUTO_UPDATE` overrides the default: `off` disables entirely; `check` polls and reports availability
18
- * (via /api/state and the log) but never installs; `on` forces auto when the gates allow it.
19
- *
20
- * Stdlib + global fetch only — no runtime deps, no transform-requiring syntax (keeps the relay strip-clean).
21
- */
22
- import { execFile } from 'node:child_process'
23
- import fs from 'node:fs'
24
- import path from 'node:path'
25
- import { promisify } from 'node:util'
26
-
27
- const execFileP = promisify(execFile)
28
-
29
- const NAME = 'conductor-remote'
30
- const projectDir = path.resolve(import.meta.dirname, '..')
31
- const REGISTRY = process.env.NPM_REGISTRY ?? 'https://registry.npmjs.org'
32
- const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000
33
- const FIRST_DELAY_MS = 90 * 1000
34
-
35
- export type UpdateMode = 'off' | 'check' | 'auto'
36
-
37
- export interface UpdateStatus {
38
- /** Version this process is running (from the package's own package.json). */
39
- current: string
40
- /** Latest version seen on the registry, or null before the first successful check. */
41
- latest: string | null
42
- /** True when `latest` is a strictly higher release than `current`. */
43
- available: boolean
44
- /** Epoch ms of the last successful registry check, or null. */
45
- checkedAt: number | null
46
- /** Effective mode after the gates are applied. */
47
- mode: UpdateMode
48
- /** Last check/install error message, or null. */
49
- lastError: string | null
50
- }
51
-
52
- function readVersion(): string {
53
- try {
54
- const pkg = JSON.parse(fs.readFileSync(path.join(projectDir, 'package.json'), 'utf8')) as { version?: string }
55
- return pkg.version ?? '0.0.0'
56
- } catch {
57
- return '0.0.0'
58
- }
59
- }
60
-
61
- const CURRENT = readVersion()
62
-
63
- const status: UpdateStatus = {
64
- current: CURRENT,
65
- latest: null,
66
- available: false,
67
- checkedAt: null,
68
- mode: 'off',
69
- lastError: null
70
- }
71
-
72
- /** Snapshot of the updater state, surfaced on /api/state so the phone can show the version and any update. */
73
- export function updateStatus(): UpdateStatus {
74
- return { ...status }
75
- }
76
-
77
- /** Parse `x.y.z` (ignoring any prerelease/build suffix) into a comparable tuple; null if unparseable. */
78
- function parseVersion(v: string): [number, number, number] | null {
79
- const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v.trim())
80
- return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null
81
- }
82
-
83
- /** True when `candidate` is a strictly higher release than `base` (prereleases collapse to their x.y.z). */
84
- function isNewer(candidate: string, base: string): boolean {
85
- const a = parseVersion(candidate)
86
- const b = parseVersion(base)
87
- if (!a || !b) return false
88
- for (let i = 0; i < 3; i++) {
89
- if (a[i] > b[i]) return true
90
- if (a[i] < b[i]) return false
91
- }
92
- return false
93
- }
94
-
95
- async function fetchLatest(): Promise<string | null> {
96
- // The `/latest` sub-endpoint serves the full manifest as application/json; the abbreviated
97
- // `vnd.npm.install-v1+json` media type is only valid on the packument root and 406s here.
98
- const res = await fetch(`${REGISTRY}/${NAME}/latest`, {
99
- headers: { accept: 'application/json' },
100
- signal: AbortSignal.timeout(10_000)
101
- })
102
- if (!res.ok) throw new Error(`registry ${res.status}`)
103
- const body = (await res.json()) as { version?: string }
104
- return body.version ?? null
105
- }
106
-
107
- /** Resolve npm next to the running node (Homebrew/nvm keep them in one bin dir); fall back to PATH. */
108
- function npmBin(): string {
109
- const adjacent = path.join(path.dirname(process.execPath), 'npm')
110
- return fs.existsSync(adjacent) ? adjacent : 'npm'
111
- }
112
-
113
- async function installLatest(): Promise<void> {
114
- await execFileP(npmBin(), ['install', '-g', `${NAME}@latest`], {
115
- timeout: 300_000,
116
- env: { ...process.env, npm_config_yes: 'true' }
117
- })
118
- }
119
-
120
- function log(msg: string): void {
121
- console.info(`[auto-update] ${msg}`)
122
- }
123
-
124
- /**
125
- * Effective mode. Precedence: explicit AUTO_UPDATE > gated default.
126
- * off — disabled. check — poll + report, never install. auto — poll + install + self-restart.
127
- * `auto` (default when unset, or when AUTO_UPDATE=on) requires BOTH gates; without them, an explicit
128
- * `on` degrades to `check` (visibility without an unsafe install) and an unset default degrades to `off`
129
- * (a dev `yarn start` or worktree daemon stays silent).
130
- */
131
- function resolveMode(): UpdateMode {
132
- const raw = process.env.AUTO_UPDATE?.trim().toLowerCase()
133
- if (raw === 'off' || raw === 'false' || raw === '0') return 'off'
134
- if (raw === 'check' || raw === 'notify') return 'check'
135
- const managed = process.env.CONDUCTOR_REMOTE_MANAGED === '1'
136
- const published = !fs.existsSync(path.join(projectDir, '.git'))
137
- const canAuto = managed && published
138
- if (raw === 'on' || raw === 'auto' || raw === '1' || raw === 'true') return canAuto ? 'auto' : 'check'
139
- return canAuto ? 'auto' : 'off'
140
- }
141
-
142
- let inFlight = false
143
-
144
- async function runCheck(mode: 'check' | 'auto'): Promise<void> {
145
- if (inFlight) return
146
- inFlight = true
147
- try {
148
- const latest = await fetchLatest()
149
- status.latest = latest
150
- status.checkedAt = Date.now()
151
- status.available = latest != null && isNewer(latest, CURRENT)
152
- status.lastError = null
153
- if (!status.available || latest == null) return
154
- if (mode === 'check') {
155
- log(`update available: ${CURRENT} → ${latest} (AUTO_UPDATE=check — not installing)`)
156
- return
157
- }
158
- log(`updating ${CURRENT} → ${latest} via \`npm i -g ${NAME}@latest\`…`)
159
- await installLatest()
160
- log(`installed ${latest}; restarting to apply (launchd KeepAlive brings the relay back).`)
161
- // Let the log line flush, then exit; KeepAlive respawns us into the new code.
162
- setTimeout(() => process.exit(0), 500).unref()
163
- } catch (err) {
164
- status.lastError = err instanceof Error ? err.message : String(err)
165
- log(`check/update failed: ${status.lastError}`)
166
- } finally {
167
- inFlight = false
168
- }
169
- }
170
-
171
- /** Start the periodic self-updater. Safe to call unconditionally — it no-ops unless the gates pass. */
172
- export function startAutoUpdate(): void {
173
- const mode = resolveMode()
174
- status.mode = mode
175
- if (mode === 'off') return
176
- log(`enabled (mode=${mode}, current=${CURRENT}); first check in ${FIRST_DELAY_MS / 1000}s, then every 6h.`)
177
- setTimeout(() => void runCheck(mode), FIRST_DELAY_MS).unref()
178
- setInterval(() => void runCheck(mode), CHECK_INTERVAL_MS).unref()
179
- }