moi-computer 0.6.0 → 0.6.1-next.0

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,786 @@
1
+ // `moi service` mechanics: run the moi server as a user-level service that
2
+ // starts on login, restarts on crash, and survives reboots — launchd on macOS,
3
+ // a systemd user unit on Linux, no third-party process manager.
4
+ //
5
+ // The unit execs the `moi` bin from PATH directly (not via a launcher): bin
6
+ // links survive package updates under every package manager, the shebang/shim
7
+ // resolves `bun` from the captured PATH, and with MOI_SERVER=1 in the unit env
8
+ // the launched process IS the server — so the service manager supervises the
9
+ // real thing, not a wrapper that spawned it.
10
+ //
11
+ // The environment is captured once, at install time (decided in the RFC — no
12
+ // runtime env file), and it is an ALLOWLIST, not a shell snapshot: PATH plus
13
+ // system basics, proxy settings, and moi/agent vars. The server itself reads
14
+ // almost nothing ambient, agent secrets have a proper channel (workspace env
15
+ // overlays every agent session), and anything custom can be captured by name
16
+ // with `moi service install --env KEY`. PATH is handled deliberately — the
17
+ // running bun's dir is prepended so the unit always finds the interpreter
18
+ // that installed it.
19
+ import { existsSync } from 'node:fs'
20
+ import { copyFile, mkdir, readFile, rm, stat, truncate, writeFile } from 'node:fs/promises'
21
+ import { homedir, userInfo } from 'node:os'
22
+ import { dirname, join } from 'node:path'
23
+
24
+ import { CONTROL_PORT } from './constants'
25
+ import { DATA_DIR } from './data-dir'
26
+ import { mergeSearchPaths } from './harness/shell-path'
27
+ import { PACKAGE_ROOT } from './version'
28
+
29
+ // ---- identity ---------------------------------------------------------------
30
+
31
+ export const LAUNCHD_LABEL = 'computer.moi.server'
32
+ export const SYSTEMD_UNIT = 'moi.service'
33
+
34
+ export type ServicePlatform = 'darwin' | 'linux'
35
+
36
+ export function servicePlatform(): ServicePlatform {
37
+ if (process.platform === 'darwin' || process.platform === 'linux') return process.platform
38
+ throw new Error(`moi service supports macOS and Linux (this is ${process.platform}).`)
39
+ }
40
+
41
+ export function serviceUnitPath(platform: ServicePlatform = servicePlatform()): string {
42
+ if (platform === 'darwin') {
43
+ return join(homedir(), 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`)
44
+ }
45
+ const configHome = process.env.XDG_CONFIG_HOME || join(homedir(), '.config')
46
+ return join(configHome, 'systemd', 'user', SYSTEMD_UNIT)
47
+ }
48
+
49
+ // Server stdout/stderr under launchd (systemd captures to the journal instead).
50
+ // Lives in the moi data dir so `MOI_DATA_DIR` isolates tests.
51
+ export function serviceLogPath(): string {
52
+ return join(DATA_DIR, 'logs', 'server.log')
53
+ }
54
+
55
+ // ---- install analysis -------------------------------------------------------
56
+
57
+ export type InstallAnalysis =
58
+ | { kind: 'global'; root: string; bin: string }
59
+ | { kind: 'checkout'; root: string; reason: string }
60
+ | { kind: 'no-bin'; root: string }
61
+
62
+ // A service (and `moi update`) only makes sense for a real global install: a
63
+ // published package ships a prebuilt client in `dist/` and no `.git`, and its
64
+ // `moi` bin resolves on PATH. A source checkout or `bun link` fails these
65
+ // checks and is refused with the reason.
66
+ export function analyzeInstall(
67
+ root: string = PACKAGE_ROOT,
68
+ which: (cmd: string) => string | null = cmd => Bun.which(cmd)
69
+ ): InstallAnalysis {
70
+ if (existsSync(join(root, '.git'))) {
71
+ return { kind: 'checkout', root, reason: 'git checkout' }
72
+ }
73
+ if (!existsSync(join(root, 'dist', 'index.html'))) {
74
+ return { kind: 'checkout', root, reason: 'no prebuilt client in dist/' }
75
+ }
76
+ const bin = which('moi')
77
+ if (!bin) return { kind: 'no-bin', root }
78
+ return { kind: 'global', root, bin }
79
+ }
80
+
81
+ // ---- environment capture ----------------------------------------------------
82
+
83
+ // What the unit captures is an allowlist, not a shell snapshot. The server's
84
+ // own code reads almost nothing ambient (HOME, PATH, XDG dirs), agent secrets
85
+ // have a proper channel (workspace env — `moi env`/.env — overlays every
86
+ // agent session), and a full snapshot would bake every exported shell secret
87
+ // and per-session value into a file that outlives them. Notably absent on
88
+ // purpose: HOST/PORT/HOSTNAME (shells export these; they would redirect the
89
+ // server bind), SSH_AUTH_SOCK (per-boot socket; launchd provides a fresh one
90
+ // anyway), and terminal/session state. Custom vars are captured by name via
91
+ // `moi service install --env KEY`.
92
+ const ENV_ALLOW = new Set([
93
+ // System identity and locale — agents and tools misbehave without them.
94
+ 'HOME',
95
+ 'USER',
96
+ 'LOGNAME',
97
+ 'SHELL',
98
+ 'TMPDIR',
99
+ 'LANG',
100
+ 'TZ',
101
+ // Stable XDG dirs (never the per-boot XDG_RUNTIME_DIR / XDG_SESSION_*).
102
+ 'XDG_CONFIG_HOME',
103
+ 'XDG_DATA_HOME',
104
+ 'XDG_STATE_HOME',
105
+ 'XDG_CACHE_HOME',
106
+ // Networking: proxies and corporate CA bundles, both cases.
107
+ 'HTTP_PROXY',
108
+ 'HTTPS_PROXY',
109
+ 'NO_PROXY',
110
+ 'ALL_PROXY',
111
+ 'http_proxy',
112
+ 'https_proxy',
113
+ 'no_proxy',
114
+ 'all_proxy',
115
+ 'NODE_EXTRA_CA_CERTS',
116
+ 'SSL_CERT_FILE',
117
+ 'SSL_CERT_DIR'
118
+ ])
119
+
120
+ // moi itself, the agent harnesses, and their runtimes. CLAUDE_* is
121
+ // deliberately NOT here: `moi service install` is often run by a Claude Code
122
+ // agent, and capturing that session's runtime vars (CLAUDE_CODE_CHILD_SESSION
123
+ // and friends) would bake "you are inside a Claude Code session" into the
124
+ // daemon permanently, skewing every agent it spawns. Config-style CLAUDE_*
125
+ // vars can be captured explicitly with --env.
126
+ const ENV_ALLOW_PREFIXES = ['MOI_', 'ANTHROPIC_', 'OPENCLAW_', 'OPENAI_', 'PUBLIC_', 'BUN_', 'LC_']
127
+
128
+ // Runtime flags the unit stamps itself — never inherited from the installing
129
+ // shell (a dev shell must not bake MOI_DEV into the service, and an
130
+ // agent-run install must not bake its MOI_AGENT marker into the daemon).
131
+ const ENV_OWNED = new Set(['MOI_SERVER', 'MOI_SERVICE', 'MOI_DEV', 'MOI_DEBUG', 'MOI_AGENT'])
132
+
133
+ const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/
134
+
135
+ // A value the unit formats can hold: no control characters (unit files are
136
+ // line-based, plists are XML, and things like LESS_TERMCAP_* carry raw ESC).
137
+ function capturableValue(value: string | undefined): value is string {
138
+ // eslint-disable-next-line no-control-regex
139
+ return value !== undefined && value !== '' && !/[\0-\x1f\x7f]/.test(value)
140
+ }
141
+
142
+ // Build the unit environment: the allowlist above, plus any extra keys the
143
+ // user named at install time (still read from the installing shell — captured
144
+ // at install, no runtime env file). PATH gets the running bun's dir
145
+ // prepended, and MOI_SERVER/MOI_SERVICE mark the process as the
146
+ // service-managed server.
147
+ export function captureServiceEnv(
148
+ base: Record<string, string | undefined> = process.env,
149
+ execDir: string = dirname(process.execPath),
150
+ extraKeys: string[] = []
151
+ ): Record<string, string> {
152
+ const extras = new Set(extraKeys)
153
+ const env: Record<string, string> = {}
154
+ for (const [key, value] of Object.entries(base)) {
155
+ if (!ENV_KEY_RE.test(key)) continue
156
+ if (ENV_OWNED.has(key)) continue
157
+ const allowed =
158
+ ENV_ALLOW.has(key) || extras.has(key) || ENV_ALLOW_PREFIXES.some(p => key.startsWith(p))
159
+ if (!allowed) continue
160
+ if (!capturableValue(value)) continue
161
+ env[key] = value
162
+ }
163
+ env.PATH = mergeSearchPaths(execDir, base.PATH)
164
+ env.MOI_SERVER = '1'
165
+ env.MOI_SERVICE = '1'
166
+ return env
167
+ }
168
+
169
+ // ---- unit file generation ---------------------------------------------------
170
+
171
+ export type ServiceSpec = {
172
+ // Absolute path of the `moi` bin the unit execs (from PATH, stable across
173
+ // package updates).
174
+ bin: string
175
+ env: Record<string, string>
176
+ // Working directory: a neutral, stable dir (home) — never the install tree,
177
+ // which package managers replace on update (see server-cwd.ts).
178
+ cwd: string
179
+ logPath: string
180
+ }
181
+
182
+ function xmlEscape(s: string): string {
183
+ return s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
184
+ }
185
+
186
+ // launchd user agent. ProgramArguments execs the moi bin directly — argv[0]'s
187
+ // basename is what macOS shows as the login item, so wrapping in /bin/sh
188
+ // would surface an anonymous "sh" entry (verified on a real Mac). The
189
+ // missing-interpreter case (bun moved/uninstalled → shebang dies with 127) is
190
+ // therefore a throttled respawn, not a graceful idle: ThrottleInterval=60
191
+ // caps it at one attempt a minute, and `moi service` status flags a unit PATH
192
+ // with no bun on it — accepted residual.
193
+ //
194
+ // KeepAlive.SuccessfulExit=false means: restart on crash (non-zero exit),
195
+ // stop respawning after a deliberate exit 0 — which is how the server signals
196
+ // a permanent startup failure (port taken, config error) under MOI_SERVICE,
197
+ // so a broken unit idles instead of respawn-looping.
198
+ export function launchdPlist(spec: ServiceSpec): string {
199
+ const envEntries = Object.keys(spec.env)
200
+ .sort()
201
+ .map(
202
+ key => `\t\t<key>${xmlEscape(key)}</key>\n\t\t<string>${xmlEscape(spec.env[key])}</string>`
203
+ )
204
+ .join('\n')
205
+ return `<?xml version="1.0" encoding="UTF-8"?>
206
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
207
+ <plist version="1.0">
208
+ <dict>
209
+ \t<key>Label</key>
210
+ \t<string>${LAUNCHD_LABEL}</string>
211
+ \t<key>ProgramArguments</key>
212
+ \t<array>
213
+ \t\t<string>${xmlEscape(spec.bin)}</string>
214
+ \t\t<string>start</string>
215
+ \t</array>
216
+ \t<key>RunAtLoad</key>
217
+ \t<true/>
218
+ \t<key>KeepAlive</key>
219
+ \t<dict>
220
+ \t\t<key>SuccessfulExit</key>
221
+ \t\t<false/>
222
+ \t</dict>
223
+ \t<key>ThrottleInterval</key>
224
+ \t<integer>60</integer>
225
+ \t<key>WorkingDirectory</key>
226
+ \t<string>${xmlEscape(spec.cwd)}</string>
227
+ \t<key>StandardOutPath</key>
228
+ \t<string>${xmlEscape(spec.logPath)}</string>
229
+ \t<key>StandardErrorPath</key>
230
+ \t<string>${xmlEscape(spec.logPath)}</string>
231
+ \t<key>ExitTimeOut</key>
232
+ \t<integer>15</integer>
233
+ \t<key>EnvironmentVariables</key>
234
+ \t<dict>
235
+ ${envEntries}
236
+ \t</dict>
237
+ </dict>
238
+ </plist>
239
+ `
240
+ }
241
+
242
+ // systemd quoting: values live inside "…" where `\` and `"` are escaped, and
243
+ // `%` doubles so specifier expansion never fires on captured values.
244
+ function systemdQuote(s: string): string {
245
+ return '"' + s.replaceAll('\\', '\\\\').replaceAll('"', '\\"').replaceAll('%', '%%') + '"'
246
+ }
247
+
248
+ // systemd user unit. Restart=on-failure restarts crashes but not the
249
+ // deliberate exit 0 the server uses for permanent startup failures, and the
250
+ // StartLimit gives up after 5 failed starts in 60s instead of looping forever
251
+ // (`moi service restart` resets the limit).
252
+ export function systemdUnit(spec: ServiceSpec): string {
253
+ const envLines = Object.keys(spec.env)
254
+ .sort()
255
+ .map(key => `Environment=${systemdQuote(`${key}=${spec.env[key]}`)}`)
256
+ .join('\n')
257
+ return `[Unit]
258
+ Description=moi server
259
+
260
+ StartLimitIntervalSec=60
261
+ StartLimitBurst=5
262
+
263
+ [Service]
264
+ ExecStart=${systemdQuote(spec.bin)} start
265
+ WorkingDirectory=${spec.cwd}
266
+ Restart=on-failure
267
+ RestartSec=2
268
+ TimeoutStopSec=10
269
+ ${envLines}
270
+
271
+ [Install]
272
+ WantedBy=default.target
273
+ `
274
+ }
275
+
276
+ function xmlUnescape(s: string): string {
277
+ return s.replaceAll('&lt;', '<').replaceAll('&gt;', '>').replaceAll('&amp;', '&')
278
+ }
279
+
280
+ function systemdUnquote(s: string): string {
281
+ return s.replaceAll('%%', '%').replaceAll('\\"', '"').replaceAll('\\\\', '\\')
282
+ }
283
+
284
+ // Pull the exec path back out of a unit file this module wrote, to detect a
285
+ // captured bin that has gone stale (moved/uninstalled) in `moi service` status.
286
+ // darwin: the first ProgramArguments string; linux: the quoted ExecStart word.
287
+ export function parseUnitBin(content: string, platform: ServicePlatform): string | null {
288
+ if (platform === 'darwin') {
289
+ const m = content.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)
290
+ return m ? xmlUnescape(m[1]) : null
291
+ }
292
+ const m = content.match(/^ExecStart="(.*)" start$/m)
293
+ return m ? systemdUnquote(m[1]) : null
294
+ }
295
+
296
+ // The PATH the unit will hand the server, read back out of the unit file —
297
+ // so status can tell when no `bun` remains anywhere on it (the moi bin's
298
+ // `#!/usr/bin/env bun` then dies at exec, before any moi code runs).
299
+ export function parseUnitSearchPath(content: string, platform: ServicePlatform): string | null {
300
+ if (platform === 'darwin') {
301
+ const m = content.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/)
302
+ return m ? xmlUnescape(m[1]) : null
303
+ }
304
+ const m = content.match(/^Environment="PATH=(.*)"$/m)
305
+ return m ? systemdUnquote(m[1]) : null
306
+ }
307
+
308
+ export function bunOnSearchPath(searchPath: string): boolean {
309
+ return searchPath.split(':').some(dir => dir && existsSync(join(dir, 'bun')))
310
+ }
311
+
312
+ // ---- process helpers --------------------------------------------------------
313
+
314
+ type RunResult = { code: number; stdout: string; stderr: string }
315
+
316
+ async function run(cmd: string[]): Promise<RunResult> {
317
+ try {
318
+ const proc = Bun.spawn(cmd, { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' })
319
+ const [code, stdout, stderr] = await Promise.all([
320
+ proc.exited,
321
+ new Response(proc.stdout).text(),
322
+ new Response(proc.stderr).text()
323
+ ])
324
+ return { code, stdout, stderr }
325
+ } catch (err) {
326
+ // Spawn itself failed — the binary (launchctl/systemctl/…) is missing.
327
+ return { code: 127, stdout: '', stderr: String(err) }
328
+ }
329
+ }
330
+
331
+ function uid(): number {
332
+ return process.getuid?.() ?? 0
333
+ }
334
+
335
+ function username(): string {
336
+ try {
337
+ return userInfo().username
338
+ } catch {
339
+ return process.env.USER ?? ''
340
+ }
341
+ }
342
+
343
+ // ---- running-server introspection -------------------------------------------
344
+
345
+ export type ServerInfo = { version: string; pid: number; port: number; service: boolean }
346
+
347
+ // Ask the running server who it is over the control port. Resolves null when
348
+ // no server is up — or when an older server (without `server:info`) is; pair
349
+ // with a plain connect check to tell those apart.
350
+ export function queryServerInfo(timeoutMs = 1500): Promise<ServerInfo | null> {
351
+ return new Promise(resolvePromise => {
352
+ let settled = false
353
+ const settle = (value: ServerInfo | null) => {
354
+ if (settled) return
355
+ settled = true
356
+ resolvePromise(value)
357
+ }
358
+ let ws: WebSocket
359
+ try {
360
+ ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
361
+ } catch {
362
+ settle(null)
363
+ return
364
+ }
365
+ const timer = setTimeout(() => {
366
+ try {
367
+ ws.close()
368
+ } catch {}
369
+ settle(null)
370
+ }, timeoutMs)
371
+ ws.onopen = () => ws.send(JSON.stringify({ type: 'server:info' }))
372
+ ws.onmessage = event => {
373
+ clearTimeout(timer)
374
+ try {
375
+ const data = JSON.parse(String(event.data)) as Partial<ServerInfo>
376
+ if (typeof data.version === 'string') {
377
+ settle({
378
+ version: data.version,
379
+ pid: typeof data.pid === 'number' ? data.pid : 0,
380
+ port: typeof data.port === 'number' ? data.port : 0,
381
+ service: data.service === true
382
+ })
383
+ } else {
384
+ settle(null)
385
+ }
386
+ } catch {
387
+ settle(null)
388
+ }
389
+ ws.close()
390
+ }
391
+ ws.onerror = () => {
392
+ clearTimeout(timer)
393
+ settle(null)
394
+ }
395
+ })
396
+ }
397
+
398
+ // Poll until the (re)started server answers `server:info`, or time runs out.
399
+ // `ignorePid` skips replies from the outgoing server: launchd's kickstart -k
400
+ // kills asynchronously, so right after a restart the old process can still be
401
+ // draining on the control port — its answer must not pass for the new one.
402
+ export async function waitForServerInfo(
403
+ timeoutMs = 12_000,
404
+ ignorePid?: number
405
+ ): Promise<ServerInfo | null> {
406
+ const deadline = Date.now() + timeoutMs
407
+ while (Date.now() < deadline) {
408
+ const info = await queryServerInfo(900)
409
+ if (info && (ignorePid === undefined || info.pid !== ignorePid)) return info
410
+ await Bun.sleep(300)
411
+ }
412
+ return null
413
+ }
414
+
415
+ // ---- linux user-manager + linger --------------------------------------------
416
+
417
+ // A systemd *user* manager only runs inside a logind session (or with
418
+ // lingering enabled). Without one, every `systemctl --user` call fails with a
419
+ // bus error — detect that up front so install can explain instead of spraying
420
+ // raw dbus errors.
421
+ export async function userManagerAvailable(): Promise<boolean> {
422
+ const res = await run(['systemctl', '--user', 'is-system-running'])
423
+ const out = (res.stdout + res.stderr).trim()
424
+ return /\b(running|degraded|starting|initializing|maintenance)\b/.test(out)
425
+ }
426
+
427
+ export type LingerState = 'enabled' | 'disabled' | 'unknown'
428
+
429
+ // Without lingering, a user's services stop when their last login session ends
430
+ // — on a headless box the service would die with the SSH session.
431
+ export async function lingerState(): Promise<LingerState> {
432
+ const user = username()
433
+ if (!user) return 'unknown'
434
+ const res = await run(['loginctl', 'show-user', user, '--property=Linger'])
435
+ if (res.code !== 0) return 'unknown'
436
+ if (res.stdout.includes('Linger=yes')) return 'enabled'
437
+ if (res.stdout.includes('Linger=no')) return 'disabled'
438
+ return 'unknown'
439
+ }
440
+
441
+ export async function tryEnableLinger(): Promise<boolean> {
442
+ // Self-linger needs no root on stock polkit; failure is surfaced as a hint,
443
+ // not an error — the service still works for logged-in sessions.
444
+ const res = await run(['loginctl', 'enable-linger'])
445
+ if (res.code !== 0) return false
446
+ return (await lingerState()) === 'enabled'
447
+ }
448
+
449
+ // ---- service state ----------------------------------------------------------
450
+
451
+ export type ServiceRuntime = {
452
+ // Loaded/active state as one human-readable word: 'running', 'idle',
453
+ // 'failed', 'not-loaded', 'unavailable' (no user manager).
454
+ state: string
455
+ pid: number | null
456
+ detail: string | null
457
+ }
458
+
459
+ // Parse `launchctl print` output. States can be multi-word (`not running`,
460
+ // `spawn scheduled`), so capture to end of line; `not running` maps onto this
461
+ // module's 'idle' vocabulary.
462
+ export function parseLaunchdPrint(stdout: string): ServiceRuntime {
463
+ const pid = stdout.match(/\bpid = (\d+)/)
464
+ const state = stdout.match(/\bstate = ([^\n]+)/)
465
+ const raw = state?.[1].trim()
466
+ return {
467
+ state: raw === 'not running' ? 'idle' : (raw ?? (pid ? 'running' : 'idle')),
468
+ pid: pid ? Number(pid[1]) : null,
469
+ detail: null
470
+ }
471
+ }
472
+
473
+ export async function serviceRuntime(
474
+ platform: ServicePlatform = servicePlatform()
475
+ ): Promise<ServiceRuntime> {
476
+ if (platform === 'darwin') {
477
+ const res = await run(['launchctl', 'print', `gui/${uid()}/${LAUNCHD_LABEL}`])
478
+ if (res.code !== 0) return { state: 'not-loaded', pid: null, detail: null }
479
+ return parseLaunchdPrint(res.stdout)
480
+ }
481
+ if (!(await userManagerAvailable())) {
482
+ return { state: 'unavailable', pid: null, detail: 'systemd user manager is not running' }
483
+ }
484
+ const res = await run([
485
+ 'systemctl',
486
+ '--user',
487
+ 'show',
488
+ SYSTEMD_UNIT,
489
+ '--property=ActiveState,SubState,MainPID,NRestarts'
490
+ ])
491
+ const props = new Map(
492
+ res.stdout
493
+ .split('\n')
494
+ .map(line => line.split('=', 2) as [string, string])
495
+ .filter(pair => pair.length === 2)
496
+ )
497
+ const active = props.get('ActiveState') ?? 'unknown'
498
+ const sub = props.get('SubState') ?? ''
499
+ const mainPid = Number(props.get('MainPID') ?? 0)
500
+ const restarts = Number(props.get('NRestarts') ?? 0)
501
+ const state = active === 'active' ? 'running' : active === 'failed' ? 'failed' : active
502
+ return {
503
+ state,
504
+ pid: mainPid > 0 ? mainPid : null,
505
+ detail:
506
+ (sub && sub !== 'running' ? sub : null) &&
507
+ `${sub}${restarts > 0 ? `, ${restarts} restarts` : ''}`
508
+ }
509
+ }
510
+
511
+ // ---- install / uninstall / restart ------------------------------------------
512
+
513
+ export class ServiceError extends Error {}
514
+
515
+ async function writeUnit(platform: ServicePlatform, content: string): Promise<string> {
516
+ const unitPath = serviceUnitPath(platform)
517
+ await mkdir(dirname(unitPath), { recursive: true })
518
+ // 0600: the captured environment can contain secrets (API keys).
519
+ await writeFile(unitPath, content, { mode: 0o600 })
520
+ return unitPath
521
+ }
522
+
523
+ // Write the unit, run the activation commands, and put things back on
524
+ // failure: a failed fresh install must not leave a half-installed unit behind
525
+ // (status would claim "installed" for a service that never activated), and a
526
+ // failed reinstall must not destroy the previous working unit.
527
+ async function writeUnitWithRollback(
528
+ platform: ServicePlatform,
529
+ content: string,
530
+ activate: () => Promise<void>
531
+ ): Promise<string> {
532
+ const unitPath = serviceUnitPath(platform)
533
+ let previous: string | null = null
534
+ try {
535
+ previous = await readFile(unitPath, 'utf8')
536
+ } catch {}
537
+ await writeUnit(platform, content)
538
+ try {
539
+ await activate()
540
+ } catch (err) {
541
+ if (previous === null) await rm(unitPath, { force: true })
542
+ else await writeFile(unitPath, previous, { mode: 0o600 })
543
+ throw err
544
+ }
545
+ return unitPath
546
+ }
547
+
548
+ export type InstallResult = {
549
+ unitPath: string
550
+ logPath: string | null
551
+ info: ServerInfo | null
552
+ notes: string[]
553
+ }
554
+
555
+ export async function installService(
556
+ opts: { port?: number; extraEnv?: string[] } = {}
557
+ ): Promise<InstallResult> {
558
+ const platform = servicePlatform()
559
+ // A reinstall replaces a running service server — remember its pid so the
560
+ // up-again poll below never mistakes the outgoing process for the new one.
561
+ const before = await queryServerInfo()
562
+ const analysis = analyzeInstall()
563
+ if (analysis.kind === 'checkout') {
564
+ throw new ServiceError(
565
+ `moi service needs a global install, not a source tree (${analysis.reason}).\n` +
566
+ ` Install one with: bun i -g moi-computer — then rerun from that \`moi\`.`
567
+ )
568
+ }
569
+ if (analysis.kind === 'no-bin') {
570
+ throw new ServiceError(
571
+ 'The `moi` command is not on PATH — the service execs it directly.\n' +
572
+ ' Install with: bun i -g moi-computer'
573
+ )
574
+ }
575
+
576
+ const extraEnv = opts.extraEnv ?? []
577
+ const env = captureServiceEnv(process.env, dirname(process.execPath), extraEnv)
578
+ // A key asked for by name must actually land — silently baking nothing
579
+ // would read as "captured" until the agent fails weeks later.
580
+ const missing = extraEnv.filter(key => !(key in env))
581
+ if (missing.length > 0) {
582
+ throw new ServiceError(
583
+ `--env ${missing.join(', ')}: not set in this shell (or the value is not capturable).`
584
+ )
585
+ }
586
+ if (opts.port) env.PORT = String(opts.port)
587
+ const spec: ServiceSpec = {
588
+ bin: analysis.bin,
589
+ env,
590
+ cwd: homedir(),
591
+ logPath: serviceLogPath()
592
+ }
593
+
594
+ const notes: string[] = []
595
+
596
+ if (platform === 'darwin') {
597
+ await mkdir(dirname(spec.logPath), { recursive: true })
598
+ const unitPath = serviceUnitPath(platform)
599
+ await writeUnitWithRollback(platform, launchdPlist(spec), async () => {
600
+ const domain = `gui/${uid()}`
601
+ // Reinstall: drop any loaded copy first so bootstrap reads the new plist.
602
+ await run(['launchctl', 'bootout', `${domain}/${LAUNCHD_LABEL}`])
603
+ // Clear a leftover `launchctl disable` so bootstrap isn't refused.
604
+ await run(['launchctl', 'enable', `${domain}/${LAUNCHD_LABEL}`])
605
+ const boot = await run(['launchctl', 'bootstrap', domain, unitPath])
606
+ if (boot.code !== 0) {
607
+ throw new ServiceError(
608
+ `launchctl bootstrap failed (${boot.stderr.trim() || `exit ${boot.code}`})`
609
+ )
610
+ }
611
+ })
612
+ notes.push('macOS may report a new login item named "moi" — that is this service.')
613
+ const info = await waitForServerInfo(12_000, before?.pid)
614
+ return { unitPath, logPath: spec.logPath, info, notes }
615
+ }
616
+
617
+ // linux
618
+ if (!(await userManagerAvailable())) {
619
+ throw new ServiceError(
620
+ 'No systemd user manager is running for this account.\n' +
621
+ ` On a headless machine enable lingering first: sudo loginctl enable-linger ${username()}\n` +
622
+ ' then log in again and rerun `moi service install`.'
623
+ )
624
+ }
625
+ const unitPath = serviceUnitPath(platform)
626
+ await writeUnitWithRollback(platform, systemdUnit(spec), async () => {
627
+ await run(['systemctl', '--user', 'daemon-reload'])
628
+ await run(['systemctl', '--user', 'reset-failed', SYSTEMD_UNIT])
629
+ const enable = await run(['systemctl', '--user', 'enable', SYSTEMD_UNIT])
630
+ if (enable.code !== 0) {
631
+ throw new ServiceError(
632
+ `systemctl enable failed (${enable.stderr.trim() || `exit ${enable.code}`})`
633
+ )
634
+ }
635
+ // `restart`, not `enable --now`: start on an already-active unit is a
636
+ // no-op, so a reinstall over a running service would keep the old process
637
+ // (old env/port/bin). restart starts an inactive unit and replaces an
638
+ // active one.
639
+ const start = await run(['systemctl', '--user', 'restart', SYSTEMD_UNIT])
640
+ if (start.code !== 0) {
641
+ throw new ServiceError(
642
+ `systemctl restart failed (${start.stderr.trim() || `exit ${start.code}`})`
643
+ )
644
+ }
645
+ })
646
+ if ((await lingerState()) !== 'enabled') {
647
+ if (await tryEnableLinger()) {
648
+ notes.push('Lingering enabled — the service keeps running after you log out.')
649
+ } else {
650
+ notes.push(
651
+ `Lingering is off: the service stops when your last session ends.\n` +
652
+ ` Enable it with: loginctl enable-linger (or: sudo loginctl enable-linger ${username()})`
653
+ )
654
+ }
655
+ }
656
+ const info = await waitForServerInfo(12_000, before?.pid)
657
+ return { unitPath, logPath: null, info, notes }
658
+ }
659
+
660
+ export async function uninstallService(): Promise<{ unitPath: string; existed: boolean }> {
661
+ const platform = servicePlatform()
662
+ const unitPath = serviceUnitPath(platform)
663
+ const existed = existsSync(unitPath)
664
+ if (platform === 'darwin') {
665
+ await run(['launchctl', 'bootout', `gui/${uid()}/${LAUNCHD_LABEL}`])
666
+ await rm(unitPath, { force: true })
667
+ return { unitPath, existed }
668
+ }
669
+ // Best-effort even without a user manager — removing the unit file is what
670
+ // stops it coming back.
671
+ await run(['systemctl', '--user', 'disable', '--now', SYSTEMD_UNIT])
672
+ await rm(unitPath, { force: true })
673
+ await run(['systemctl', '--user', 'daemon-reload'])
674
+ await run(['systemctl', '--user', 'reset-failed', SYSTEMD_UNIT])
675
+ return { unitPath, existed }
676
+ }
677
+
678
+ export async function restartService(): Promise<ServerInfo | null> {
679
+ const platform = servicePlatform()
680
+ const unitPath = serviceUnitPath(platform)
681
+ if (!existsSync(unitPath)) {
682
+ throw new ServiceError('The service is not installed — run `moi service install` first.')
683
+ }
684
+ const before = await queryServerInfo()
685
+ if (platform === 'darwin') {
686
+ const domain = `gui/${uid()}`
687
+ const kick = await run(['launchctl', 'kickstart', '-k', `${domain}/${LAUNCHD_LABEL}`])
688
+ if (kick.code !== 0) {
689
+ // Not loaded in this login session (e.g. installed long ago, then
690
+ // bootout) — bootstrap it back in.
691
+ const boot = await run(['launchctl', 'bootstrap', domain, unitPath])
692
+ if (boot.code !== 0) {
693
+ throw new ServiceError(
694
+ `launchctl kickstart failed (${kick.stderr.trim() || `exit ${kick.code}`})`
695
+ )
696
+ }
697
+ }
698
+ return waitForServerInfo(12_000, before?.pid)
699
+ }
700
+ if (!(await userManagerAvailable())) {
701
+ throw new ServiceError('No systemd user manager is running for this account.')
702
+ }
703
+ await run(['systemctl', '--user', 'reset-failed', SYSTEMD_UNIT])
704
+ const res = await run(['systemctl', '--user', 'restart', SYSTEMD_UNIT])
705
+ if (res.code !== 0) {
706
+ throw new ServiceError(`systemctl restart failed (${res.stderr.trim() || `exit ${res.code}`})`)
707
+ }
708
+ return waitForServerInfo(12_000, before?.pid)
709
+ }
710
+
711
+ // ---- status assembly --------------------------------------------------------
712
+
713
+ export type ServiceStatus = {
714
+ platform: ServicePlatform
715
+ installed: boolean
716
+ unitPath: string
717
+ logPath: string | null
718
+ runtime: ServiceRuntime | null
719
+ // The bin the unit execs, and whether it still exists (a moved/reinstalled
720
+ // moi leaves a stale unit behind).
721
+ bin: string | null
722
+ binMissing: boolean
723
+ // No `bun` anywhere on the unit's captured PATH — the bin's shebang dies at
724
+ // exec, so the service respawn-throttles without ever running moi code.
725
+ bunMissing: boolean
726
+ linger: LingerState | null
727
+ }
728
+
729
+ export async function serviceStatus(): Promise<ServiceStatus> {
730
+ const platform = servicePlatform()
731
+ const unitPath = serviceUnitPath(platform)
732
+ const installed = existsSync(unitPath)
733
+ let bin: string | null = null
734
+ let binMissing = false
735
+ let bunMissing = false
736
+ if (installed) {
737
+ try {
738
+ const content = await readFile(unitPath, 'utf8')
739
+ bin = parseUnitBin(content, platform)
740
+ binMissing = bin !== null && !existsSync(bin)
741
+ const searchPath = parseUnitSearchPath(content, platform)
742
+ bunMissing = searchPath !== null && !bunOnSearchPath(searchPath)
743
+ } catch {}
744
+ }
745
+ return {
746
+ platform,
747
+ installed,
748
+ unitPath,
749
+ logPath: platform === 'darwin' ? serviceLogPath() : null,
750
+ runtime: installed ? await serviceRuntime(platform) : null,
751
+ bin,
752
+ binMissing,
753
+ bunMissing,
754
+ linger: platform === 'linux' ? await lingerState() : null
755
+ }
756
+ }
757
+
758
+ // ---- launchd log rotation ---------------------------------------------------
759
+
760
+ // launchd redirects stdout/stderr to a file and never rotates it. The server
761
+ // rotates its own log with copy-then-truncate: launchd opens the file with
762
+ // O_APPEND, so writes after truncate land at the new end — no fd juggling.
763
+ // (systemd needs none of this; journald bounds the journal.)
764
+ export const SERVICE_LOG_MAX_BYTES = 5 * 1024 * 1024
765
+
766
+ export async function rotateServiceLog(logPath = serviceLogPath()): Promise<boolean> {
767
+ try {
768
+ const info = await stat(logPath)
769
+ if (info.size <= SERVICE_LOG_MAX_BYTES) return false
770
+ await copyFile(logPath, logPath + '.old')
771
+ await truncate(logPath, 0)
772
+ return true
773
+ } catch {
774
+ return false
775
+ }
776
+ }
777
+
778
+ const LOG_ROTATION_CHECK_MS = 6 * 60 * 60 * 1000
779
+
780
+ // Called from server boot; a no-op unless this process is the service-managed
781
+ // server on macOS (the only setup that logs to a file).
782
+ export function startServiceLogMaintenance(): void {
783
+ if (!process.env.MOI_SERVICE || process.platform !== 'darwin') return
784
+ void rotateServiceLog()
785
+ setInterval(() => void rotateServiceLog(), LOG_ROTATION_CHECK_MS).unref()
786
+ }