moi-computer 0.6.0 → 0.7.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.
package/server/status.ts CHANGED
@@ -11,6 +11,7 @@ import { WORKER_LIMITS, type WorkerDebugInfo, getWorkersDebugSnapshot } from './
11
11
  import { allHarnesses } from './harness/registry'
12
12
  import { tildify } from './registry'
13
13
  import { getClientCount } from './state'
14
+ import { VERSION } from './version'
14
15
 
15
16
  const STARTED_AT = Date.now()
16
17
 
@@ -70,6 +71,7 @@ export function renderStatus(): string {
70
71
  lines.push('moi server status')
71
72
  lines.push('=================')
72
73
  lines.push('')
74
+ lines.push(`version ${VERSION}${process.env.MOI_SERVICE ? ' (service-managed)' : ''}`)
73
75
  lines.push(`uptime ${fmtDuration(now - STARTED_AT)}`)
74
76
  lines.push(`http port ${PORT}`)
75
77
  lines.push(`control port ${CONTROL_PORT}`)
@@ -0,0 +1,141 @@
1
+ // `moi update` mechanics: check the npm registry for the latest published
2
+ // version, find the package manager that owns the current global install, and
3
+ // update through it — never around it, so no second shadowing install appears.
4
+ // Manual command only; nothing here runs in the background.
5
+ import { realpathSync } from 'node:fs'
6
+
7
+ import { PACKAGE_ROOT } from './version'
8
+
9
+ export const PACKAGE_NAME = 'moi-computer'
10
+
11
+ // Test seam: point at a local mock registry (`MOI_NPM_REGISTRY`).
12
+ function registryBase(): string {
13
+ return (process.env.MOI_NPM_REGISTRY || 'https://registry.npmjs.org').replace(/\/$/, '')
14
+ }
15
+
16
+ // Resolve the `latest` dist-tag. Throws with a friendly message on network or
17
+ // registry trouble — the CLI shows it verbatim.
18
+ export async function fetchLatestVersion(pkg = PACKAGE_NAME): Promise<string> {
19
+ const url = `${registryBase()}/${pkg}/latest`
20
+ let res: Response
21
+ try {
22
+ res = await fetch(url, { signal: AbortSignal.timeout(10_000) })
23
+ } catch {
24
+ throw new Error(`Could not reach the npm registry (${registryBase()}) — check your network.`)
25
+ }
26
+ if (!res.ok) {
27
+ throw new Error(`npm registry returned ${res.status} for ${pkg} — try again later.`)
28
+ }
29
+ const data = (await res.json().catch(() => null)) as { version?: unknown } | null
30
+ if (!data || typeof data.version !== 'string') {
31
+ throw new Error('Unexpected npm registry response — try again later.')
32
+ }
33
+ return data.version
34
+ }
35
+
36
+ // `Bun.semver.order` handles prerelease precedence correctly
37
+ // (0.5.2-next.1 < 0.5.2).
38
+ export function isNewer(candidate: string, current: string): boolean {
39
+ try {
40
+ return Bun.semver.order(candidate, current) === 1
41
+ } catch {
42
+ return false
43
+ }
44
+ }
45
+
46
+ // ---- owning package manager -------------------------------------------------
47
+
48
+ export type PackageManager = 'bun' | 'npm' | 'pnpm' | 'yarn'
49
+
50
+ // Where each manager keeps its global tree leaves a recognizable path
51
+ // signature; npm's prefix is freeform, so it gets confirmed by asking npm
52
+ // itself (only when nothing else matched — `npm root -g` costs a process).
53
+ export async function detectPackageManager(
54
+ installRoot: string = safeRealpath(PACKAGE_ROOT),
55
+ npmRootDir: () => Promise<string | null> = defaultNpmRootDir
56
+ ): Promise<PackageManager | null> {
57
+ const root = installRoot.replaceAll('\\', '/')
58
+ if (root.includes('/.bun/')) return 'bun'
59
+ if (root.includes('/.pnpm/') || root.includes('/pnpm/')) return 'pnpm'
60
+ if (root.includes('/.yarn/') || root.includes('/yarn/')) return 'yarn'
61
+ const npmRoot = await npmRootDir()
62
+ if (npmRoot && root.startsWith(npmRoot.replaceAll('\\', '/').replace(/\/$/, '') + '/')) {
63
+ return 'npm'
64
+ }
65
+ return null
66
+ }
67
+
68
+ function safeRealpath(path: string): string {
69
+ try {
70
+ return realpathSync(path)
71
+ } catch {
72
+ return path
73
+ }
74
+ }
75
+
76
+ async function defaultNpmRootDir(): Promise<string | null> {
77
+ try {
78
+ const proc = Bun.spawn(['npm', 'root', '-g'], {
79
+ stdin: 'ignore',
80
+ stdout: 'pipe',
81
+ stderr: 'ignore'
82
+ })
83
+ const [code, out] = await Promise.all([proc.exited, new Response(proc.stdout).text()])
84
+ if (code !== 0) return null
85
+ const dir = out.trim()
86
+ return dir ? safeRealpath(dir) : null
87
+ } catch {
88
+ return null
89
+ }
90
+ }
91
+
92
+ // The exact global-install command per manager, pinned to the resolved version
93
+ // so the install matches what the check reported.
94
+ export function updateArgv(pm: PackageManager, version: string): string[] {
95
+ const spec = `${PACKAGE_NAME}@${version}`
96
+ switch (pm) {
97
+ case 'bun':
98
+ return ['bun', 'install', '-g', spec]
99
+ case 'npm':
100
+ return ['npm', 'install', '-g', spec]
101
+ case 'pnpm':
102
+ return ['pnpm', 'add', '-g', spec]
103
+ case 'yarn':
104
+ return ['yarn', 'global', 'add', spec]
105
+ }
106
+ }
107
+
108
+ // One manual line per manager, for when detection comes up empty.
109
+ export function manualUpdateLines(version: string): string[] {
110
+ return (['bun', 'npm', 'pnpm', 'yarn'] as const).map(pm => updateArgv(pm, version).join(' '))
111
+ }
112
+
113
+ // Run the owning package manager with live output (the user watches their own
114
+ // tool do the work). Returns the exit code.
115
+ export async function runPackageManager(argv: string[]): Promise<number> {
116
+ try {
117
+ const proc = Bun.spawn(argv, { stdin: 'ignore', stdout: 'inherit', stderr: 'inherit' })
118
+ return await proc.exited
119
+ } catch {
120
+ return 127
121
+ }
122
+ }
123
+
124
+ // Ask the freshly-updated install what version it is now, through the same bin
125
+ // users run — catching both a failed install and a PATH that resolves to some
126
+ // other, shadowing install.
127
+ export async function installedBinVersion(bin: string): Promise<string | null> {
128
+ try {
129
+ const proc = Bun.spawn([bin, 'version'], {
130
+ stdin: 'ignore',
131
+ stdout: 'pipe',
132
+ stderr: 'ignore'
133
+ })
134
+ const [code, out] = await Promise.all([proc.exited, new Response(proc.stdout).text()])
135
+ if (code !== 0) return null
136
+ const m = out.trim().match(/^(\S+)/)
137
+ return m ? m[1] : null
138
+ } catch {
139
+ return null
140
+ }
141
+ }
@@ -0,0 +1,41 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ // The package root of the code that is actually running — server and CLI both
5
+ // resolve their own tree, so a CLI from one install never reports another's
6
+ // version.
7
+ export const PACKAGE_ROOT = join(import.meta.dir, '..')
8
+
9
+ function readPackageVersion(): string {
10
+ try {
11
+ const pkg = JSON.parse(readFileSync(join(PACKAGE_ROOT, 'package.json'), 'utf8')) as {
12
+ version?: string
13
+ }
14
+ if (typeof pkg.version === 'string') return pkg.version
15
+ } catch {}
16
+ return '0.0.0'
17
+ }
18
+
19
+ // Snapshotted at module load, deliberately: after `bun i -g` swaps the install
20
+ // tree under a running server, the server must keep reporting the version of
21
+ // the code it loaded — reading package.json lazily would claim the new version
22
+ // while old code runs (and under pnpm the old realpath may not even exist).
23
+ export const VERSION = readPackageVersion()
24
+
25
+ // True for a prerelease like `0.5.2-next.1` — those are published to a dist-tag
26
+ // other than `latest`, so `moi update` leaves them alone.
27
+ export function isPrerelease(version: string): boolean {
28
+ return version.includes('-')
29
+ }
30
+
31
+ // `<package version> (<8-char commit>)`, e.g. `0.1.3 (27e17e80)`. The commit is
32
+ // read from git at call time, so it appears for a source/`bun link` checkout and
33
+ // is simply omitted for a published package (which ships no .git).
34
+ export function versionWithCommit(): string {
35
+ let commit = ''
36
+ try {
37
+ const out = Bun.spawnSync(['git', 'rev-parse', '--short=8', 'HEAD'], { cwd: PACKAGE_ROOT })
38
+ if (out.success) commit = out.stdout.toString().trim()
39
+ } catch {}
40
+ return commit ? `${VERSION} (${commit})` : VERSION
41
+ }
package/server/web.ts CHANGED
@@ -13,6 +13,7 @@ import { allHarnesses, harnessFor } from './harness/registry'
13
13
  import { getWorkspace } from './registry'
14
14
  import { saveSelectedSession } from './selected-session'
15
15
  import { addClient, broadcastAll, getClientCount, removeClient, sendToClient } from './state'
16
+ import { startServiceLogMaintenance } from './service'
16
17
  import { distShell, prebuilt } from './static'
17
18
  import { renderStatus } from './status'
18
19
  import { serveVendorEmojibase, serveVendorReact } from './vendor'
@@ -208,6 +209,10 @@ setInterval(() => {
208
209
  // leaves its file behind forever. See sweepOrphanAssets.
209
210
  startScratchpadSweeper()
210
211
 
212
+ // Under launchd the service log is a plain file nothing rotates — bound it
213
+ // here. No-op outside the macOS service context.
214
+ startServiceLogMaintenance()
215
+
211
216
  // Graceful shutdown. In dev the supervisor sends SIGTERM on server-file
212
217
  // changes; in any context Ctrl-C sends SIGINT. Close both servers and kill the
213
218
  // per-workspace function workers so no child processes are orphaned.