centralu 0.1.0-beta.1 → 0.1.0-beta.11

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/bin/centralu.mjs CHANGED
@@ -1,18 +1,50 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Centralu 실행기.
3
+ * The Centralu launcher.
4
4
  *
5
- * **왜 npm으로 주는가:** macOS는 앱을 검사해서 위험하다고 판정하는 게 아니라,
6
- * 파일에 붙은 `com.apple.quarantine` 딱지를 보고 개발자 신원을 따진다. 그 딱지는
7
- * **받아온 프로그램이** 붙인다 — 브라우저는 붙이고 npm은 안 붙인다. 그래서 npm으로
8
- * 설치하면 서명이 애드혹이어도 경고 없이 그냥 열린다 (docs/plans/beta-release-checklist.md §2).
5
+ * **Why this ships through npm:** macOS does not inspect the app and decide it is dangerous —
6
+ * it looks at the `com.apple.quarantine` flag attached to the file and checks the developer's
7
+ * identity from that. That flag is attached **by the program that downloaded it** — a browser
8
+ * attaches it, npm does not. So an npm install just opens with no warning even with an ad hoc
9
+ * signature (docs/plans/beta-release-checklist.md §2).
9
10
  *
10
- * 앱 본체는 아키텍처별 패키지(`centralu-darwin-arm64`)에 들어 있다. 이 패키지는
11
- * 그것을 찾아 띄우는 얇은 껍데기다 — esbuild·swc가 쓰는 것과 같은 구조.
11
+ * The app itself lives inside an architecture-specific package (`@centralu/darwin-arm64`). This
12
+ * package is a thin shell that finds it and launches it — the same structure esbuild and swc
13
+ * use.
14
+ *
15
+ * Linux is served from the same shim (issue #14). The two platforms disagree about what
16
+ * "the app" even is — macOS hands a `.app` directory to LaunchServices, Linux runs a
17
+ * self-contained AppImage itself — so that difference lives in one table (`TARGETS`)
18
+ * instead of being rediscovered in every function.
19
+ *
20
+ * Windows joined in W3 of #14. Its decisions — the exe inside the folder, a detached start,
21
+ * where `install` copies to, the WebView2 check — live in `platform.mjs` as functions of the
22
+ * platform, so they are tested on macOS CI (tooling/launcher-platform.test.ts) instead of
23
+ * being first exercised on someone's laptop.
12
24
  */
13
25
  import { execFileSync, spawn } from 'node:child_process'
14
- import { existsSync, rmSync } from 'node:fs'
26
+ import { copyDiffers, isNewer } from './semver.mjs'
27
+ import {
28
+ busyMessage,
29
+ earlyExitMessage,
30
+ executableIn,
31
+ hostDirIn,
32
+ installedPaths,
33
+ isBusyError,
34
+ launchPlan,
35
+ npmCommand,
36
+ regExe,
37
+ shortcutCommand,
38
+ targetFor,
39
+ TARGETS,
40
+ webview2MissingMessage,
41
+ webview2Status,
42
+ windowsInstall,
43
+ } from './platform.mjs'
44
+ import { parseServeArgs, printConnection, rotateToken, runServe, SERVE_HELP } from './serve.mjs'
45
+ import { chmodSync, cpSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
15
46
  import { createRequire } from 'node:module'
47
+ import { homedir } from 'node:os'
16
48
  import { dirname, join } from 'node:path'
17
49
 
18
50
  const require = createRequire(import.meta.url)
@@ -22,89 +54,338 @@ const APP_NAME = 'Centralu'
22
54
  const BUNDLE = `${APP_NAME}.app`
23
55
  const INSTALLED = `/Applications/${BUNDLE}`
24
56
 
25
- /** 아키텍처별 패키지 안의 `.app`. 못 찾으면 null */
57
+ const PLATFORM = process.platform
58
+ const HOME = homedir()
59
+
60
+ /** Where a menu entry for the app goes on freedesktop desktops */
61
+ const DESKTOP_ENTRY = join(HOME, '.local/share/applications/centralu.desktop')
62
+
63
+ /** Where `centralu install` copies the app on Windows (see `windowsInstall`) */
64
+ const WIN = PLATFORM === 'win32' ? windowsInstall(process.env, HOME) : null
65
+
66
+ /** The arch package for this machine (the table lives in platform.mjs) */
67
+ const TARGET = targetFor(PLATFORM, process.arch)
68
+
69
+ /** The app inside the architecture-specific package. null if it cannot be found. */
26
70
  function bundledApp() {
27
- for (const dep of ['centralu-darwin-arm64']) {
28
- try {
29
- return join(dirname(require.resolve(`${dep}/package.json`)), BUNDLE)
30
- } catch {
31
- // 이 아키텍처용 패키지가 안 깔린 것 — 아래에서 이유를 말한다
32
- }
71
+ if (!TARGET) return null
72
+ let root
73
+ try {
74
+ root = dirname(require.resolve(`${TARGET.pkg}/package.json`))
75
+ } catch {
76
+ return null // The package for this architecture is not installed — the reason is explained below.
33
77
  }
34
- return null
78
+ const app = join(root, TARGET.artifact)
79
+ return existsSync(executableIn(PLATFORM, app)) ? app : null
35
80
  }
36
81
 
37
82
  /**
38
- * 지금 이 맥에서 왜 못 쓰는지를 **구체적으로** 말한다.
39
- * "설치가 안 됐습니다"만 뜨면 사용자가 할 수 있는 일이 없다.
83
+ * States **specifically** why this machine cannot run it right now.
84
+ * If all that shows is "not installed", there is nothing the person can act on.
40
85
  */
41
86
  function explainMissing() {
42
- if (process.platform !== 'darwin') {
43
- return `${APP_NAME}는 macOS 앱입니다 (지금 플랫폼: ${process.platform}).`
44
- }
45
- if (process.arch !== 'arm64') {
87
+ if (!TARGET) {
88
+ // Kept as its own case: "not published for your machine" and "not published for
89
+ // Intel Macs, and here is the reason" send the user to different places.
90
+ if (PLATFORM === 'darwin') {
91
+ return (
92
+ `${APP_NAME} is Apple Silicon only for now (current architecture: ${process.arch}).\n` +
93
+ 'Intel Mac support needs native addons bundled in as well, and is tracked as separate work.'
94
+ )
95
+ }
96
+ const supported = Object.keys(TARGETS).join(', ')
46
97
  return (
47
- `${APP_NAME}는 아직 Apple Silicon 전용입니다 (지금 아키텍처: ${process.arch}).\n` +
48
- 'Intel 맥 지원은 네이티브 애드온까지 함께 묶어야 해서 별도 작업으로 잡혀 있습니다.'
98
+ `${APP_NAME} does not support ${PLATFORM}/${process.arch} yet.\n` +
99
+ `Currently supported combinations: ${supported}\n` +
100
+ 'Progress is tracked at https://github.com/ijun17/centralu/issues/14.'
49
101
  )
50
102
  }
51
103
  return (
52
- '앱 본체 패키지(centralu-darwin-arm64)를 찾지 못했습니다.\n' +
53
- '설치가 중간에 끊겼을 수 있습니다 — `npm i -g centralu`로 다시 설치해 주세요.'
104
+ `Could not find the app package (${TARGET.pkg}).\n` +
105
+ 'The install may have been interrupted — please reinstall with `npm i -g centralu`.'
54
106
  )
55
107
  }
56
108
 
109
+ /**
110
+ * The bundled host's entry (`resources/host/main.mjs`) for `centralu serve`, or exit with why not.
111
+ *
112
+ * `CENTRALU_HOST_ENTRY` points it at another host instead: a source checkout's
113
+ * `packages/agent-host/src/main.ts` while developing, or a freshly bundled `resources/host/main.mjs`.
114
+ * The tests start `serve` that way (tooling/launcher-serve.test.ts).
115
+ */
116
+ function requireHostEntry() {
117
+ if (process.env.CENTRALU_HOST_ENTRY) return process.env.CENTRALU_HOST_ENTRY
118
+ if (!TARGET) {
119
+ console.error(explainMissing())
120
+ process.exit(1)
121
+ }
122
+ let root
123
+ try {
124
+ root = dirname(require.resolve(`${TARGET.pkg}/package.json`))
125
+ } catch {
126
+ console.error(explainMissing())
127
+ process.exit(1)
128
+ }
129
+ const entry = join(hostDirIn(PLATFORM, join(root, TARGET.artifact)), 'main.mjs')
130
+ if (!existsSync(entry)) {
131
+ console.error(
132
+ `The host is missing from ${TARGET.pkg} (looked for ${entry}).\n` +
133
+ 'Linux packages published before `centralu serve` existed do not carry it. Update with `npm i -g centralu`.',
134
+ )
135
+ process.exit(1)
136
+ }
137
+ return entry
138
+ }
139
+
57
140
  function requireApp() {
58
141
  const app = bundledApp()
59
- if (!app || !existsSync(app)) {
142
+ if (!app) {
60
143
  console.error(explainMissing())
61
144
  process.exit(1)
62
145
  }
63
146
  return app
64
147
  }
65
148
 
66
- /** 앱을 띄운다. `/Applications`에 설치돼 있으면 그쪽을 먼저 쓴다 */
67
- function run(args) {
68
- const app = existsSync(INSTALLED) ? INSTALLED : requireApp()
69
- // `open`은 LaunchServices를 거친다 — Dock 아이콘·단일 인스턴스가 그래야 제대로 산다
70
- const r = spawn('open', ['-a', app, ...(args.length ? ['--args', ...args] : [])], { stdio: 'inherit' })
149
+ /**
150
+ * Launches the app. If it is installed in `/Applications` (macOS) or
151
+ * `%LOCALAPPDATA%\Programs\Centralu` (Windows), that copy is used first.
152
+ *
153
+ * Linux has no such preference, and not for lack of an equivalent: `centralu install`
154
+ * on Linux writes a launcher that points back at this same package, so there is never a
155
+ * second copy to prefer.
156
+ *
157
+ * Resolves once the launcher has nothing more to wait for. Only Windows waits at all —
158
+ * briefly, to report an exe that dies on start (see runWindows).
159
+ */
160
+ async function run(args) {
161
+ if (PLATFORM === 'darwin') {
162
+ const app = existsSync(INSTALLED) ? INSTALLED : requireApp()
163
+ // `open` goes through LaunchServices — the dock icon and single-instance behavior only
164
+ // work correctly that way.
165
+ const plan = launchPlan(PLATFORM, app, args, HOME)
166
+ const r = spawn(plan.command, plan.args, plan.options)
167
+ r.on('exit', (code) => process.exit(code ?? 0))
168
+ return
169
+ }
170
+ if (PLATFORM === 'win32') return runWindows(args)
171
+ // Linux has no LaunchServices — the AppImage is its own launcher, so run it directly.
172
+ //
173
+ // Staying attached to the terminal is on purpose. The two usual first failures on
174
+ // Linux both explain themselves on stderr and nowhere else: a missing FUSE
175
+ // ("AppImages require FUSE to run", with the workaround in the same sentence) and a
176
+ // missing system library from the loader. Detaching would hand back the shell prompt
177
+ // and throw away the one line that says what to do.
178
+ const app = requireApp()
179
+ const plan = launchPlan(PLATFORM, app, args, HOME)
180
+ const r = spawn(plan.command, plan.args, plan.options)
181
+ r.on('error', (e) => {
182
+ console.error(`Failed to run ${app}: ${e.message}`)
183
+ // EACCES here means the executable bit did not survive the trip through npm, which
184
+ // is invisible from the message alone.
185
+ if (e.code === 'EACCES') console.error(`No execute permission — run \`chmod +x "${app}"\` then try again.`)
186
+ process.exit(1)
187
+ })
71
188
  r.on('exit', (code) => process.exit(code ?? 0))
72
189
  }
73
190
 
191
+ /** How long to watch a freshly started exe for an immediate exit */
192
+ const EARLY_EXIT_MS = 3000
193
+
194
+ /**
195
+ * Windows: check WebView2, start `centralu.exe` detached, and watch it for a few seconds.
196
+ *
197
+ * The app is a GUI program, so a failure to start has nowhere to print. Without WebView2
198
+ * the exe ends before it has a window, and the person sees nothing happen at all — the
199
+ * registry check turns that into a message with the download link before anything starts.
200
+ * The short watch afterwards catches whatever the registry cannot see (a broken runtime, a
201
+ * blocked exe), then lets go so the app outlives this launcher.
202
+ */
203
+ async function runWindows(args) {
204
+ const webview = webview2Status(process.env, queryRegistry)
205
+ if (webview.state === 'missing') {
206
+ console.error(webview2MissingMessage())
207
+ process.exit(1)
208
+ }
209
+ const app = existsSync(WIN.exe) ? WIN.dir : requireApp()
210
+ const plan = launchPlan(PLATFORM, app, args, HOME)
211
+ const child = spawn(plan.command, plan.args, plan.options)
212
+ await new Promise((resolve) => {
213
+ const done = () => {
214
+ clearTimeout(timer)
215
+ child.removeAllListeners()
216
+ child.unref()
217
+ resolve()
218
+ }
219
+ const timer = setTimeout(done, EARLY_EXIT_MS)
220
+ child.on('error', (e) => {
221
+ console.error(`Failed to start ${plan.command}: ${e.message}`)
222
+ process.exitCode = 1
223
+ done()
224
+ })
225
+ child.on('exit', (code) => {
226
+ // 0 is a normal answer this early: a second start hands over to the window that is
227
+ // already open and leaves.
228
+ if (code !== 0 && code !== null) {
229
+ console.error(earlyExitMessage(code, HOME))
230
+ process.exitCode = 1
231
+ }
232
+ done()
233
+ })
234
+ })
235
+ }
236
+
237
+ /**
238
+ * `reg query <key> /v pv`: stdout, null when the key or value does not exist (reg exits 1),
239
+ * undefined when reg itself could not run.
240
+ */
241
+ function queryRegistry(key) {
242
+ try {
243
+ return execFileSync(regExe(process.env), ['query', key, '/v', 'pv'], {
244
+ encoding: 'utf8',
245
+ stdio: ['ignore', 'pipe', 'ignore'],
246
+ windowsHide: true,
247
+ })
248
+ } catch (e) {
249
+ return typeof e?.status === 'number' ? null : undefined
250
+ }
251
+ }
252
+
74
253
  /**
75
- * `/Applications`에 복사한다.
254
+ * Registers the app in the system menu.
76
255
  *
77
- * **postinstall로 몰래 하지 않는다.** 남의 `/Applications`에 조용히 쓰는 것은 신뢰를 깎고,
78
- * pnpm은 postinstall을 기본 차단한다. 사용자가 원할 때 명시적으로 부르게 한다.
256
+ * **Never done quietly through postinstall.** Writing silently into someone's `/Applications`
257
+ * erodes trust, and pnpm blocks postinstall by default anyway. This is only run when the
258
+ * person explicitly asks for it.
79
259
  */
80
260
  function install() {
81
261
  const app = requireApp()
262
+ if (PLATFORM === 'win32') return installWindows(app)
263
+ if (PLATFORM !== 'darwin') return installDesktopEntry(app)
82
264
  if (existsSync(INSTALLED)) {
83
- console.log(`기존 ${INSTALLED}를 새 버전으로 교체합니다.`)
265
+ console.log(`Replacing the existing ${INSTALLED} with the new version.`)
84
266
  rmSync(INSTALLED, { recursive: true, force: true })
85
267
  }
86
- // cp가 아니라 ditto — 번들의 권한·확장속성을 그대로 옮긴다 (서명이 깨지지 않게)
268
+ // ditto, not cp — carries over the bundle's permissions and extended attributes unchanged
269
+ // (so the signature does not break).
87
270
  execFileSync('/usr/bin/ditto', [app, INSTALLED], { stdio: 'inherit' })
88
- console.log(`설치했습니다: ${INSTALLED}`)
89
- console.log('이제 Launchpad·Spotlight에서도 찾을 수 있습니다.')
271
+ console.log(`Installed: ${INSTALLED}`)
272
+ console.log('It can now be found in Launchpad and Spotlight too.')
273
+ }
274
+
275
+ /**
276
+ * The Linux answer to "copy it into /Applications so it shows up in Launchpad".
277
+ *
278
+ * It writes a launcher, not a copy. On macOS the `.app` has to move because
279
+ * LaunchServices only indexes a few directories; on Linux the menu indexes `.desktop`
280
+ * files that may point anywhere, so pointing at the npm package leaves exactly one copy
281
+ * of the binary — and `npm i -g centralu@newer` then updates the menu entry too,
282
+ * because the path it names does not change.
283
+ */
284
+ function installDesktopEntry(app) {
285
+ const icon = join(dirname(app), 'icon.png')
286
+ const entry = [
287
+ '[Desktop Entry]',
288
+ 'Type=Application',
289
+ `Name=${APP_NAME}`,
290
+ 'Comment=Run, watch and steer several coding agents in one window',
291
+ // Quoted because the path runs through node_modules and npm prefixes can contain spaces
292
+ `Exec="${app}" %U`,
293
+ `Icon=${existsSync(icon) ? icon : 'centralu'}`,
294
+ 'Terminal=false',
295
+ 'Categories=Development;Utility;',
296
+ // Guessed, not measured: this must equal the WM class the running window reports,
297
+ // and we have no Linux desktop here to read it off. If the taskbar shows two icons
298
+ // for one window, this line is why.
299
+ 'StartupWMClass=Centralu',
300
+ '',
301
+ ].join('\n')
302
+ mkdirSync(dirname(DESKTOP_ENTRY), { recursive: true })
303
+ writeFileSync(DESKTOP_ENTRY, entry)
304
+ chmodSync(DESKTOP_ENTRY, 0o755)
305
+ console.log(`Registered: ${DESKTOP_ENTRY}`)
306
+ console.log('It can now be found in the app list too (some desktops require logging back in before it shows up).')
307
+ }
308
+
309
+ /**
310
+ * The Windows answer to "copy it into /Applications": copy the folder into
311
+ * `%LOCALAPPDATA%\Programs\Centralu` and put a shortcut in the Start menu.
312
+ *
313
+ * A copy rather than a shortcut into the npm package (the Linux shape), because Windows
314
+ * will not replace a running program's files: with the app running from the package,
315
+ * `npm i -g centralu@newer` fails. Running from the copy leaves the package free to update.
316
+ *
317
+ * The old copy is never deleted before the new one is complete. The new folder is
318
+ * assembled beside it, the old one is renamed aside, and only then is the new one moved in
319
+ * — so a copy that fails halfway, or an app that is still running, leaves the working
320
+ * install untouched rather than a folder with half its files.
321
+ */
322
+ function installWindows(app) {
323
+ const staging = `${WIN.dir}.new`
324
+ const aside = `${WIN.dir}.old-${Date.now()}`
325
+ rmSync(staging, { recursive: true, force: true })
326
+ mkdirSync(dirname(WIN.dir), { recursive: true })
327
+ cpSync(app, staging, { recursive: true })
328
+ writeFileSync(join(staging, 'centralu-version.txt'), `${pkg.version}\n`)
329
+ if (existsSync(WIN.dir)) {
330
+ console.log(`Replacing the existing ${WIN.dir} with the new version.`)
331
+ try {
332
+ renameSync(WIN.dir, aside)
333
+ } catch (e) {
334
+ rmSync(staging, { recursive: true, force: true })
335
+ if (!isBusyError(e)) throw e
336
+ console.error(busyMessage(WIN.dir))
337
+ process.exit(1)
338
+ }
339
+ }
340
+ renameSync(staging, WIN.dir)
341
+ try {
342
+ rmSync(aside, { recursive: true, force: true })
343
+ } catch {
344
+ // A rename can succeed while the old copy is running; its files then stay locked until
345
+ // it quits. Harmless — it is no longer the one anything starts — but worth a line.
346
+ console.log(`The previous copy is still in use and was left at ${aside}. Delete it after quitting ${APP_NAME}.`)
347
+ }
348
+ const sc = shortcutCommand(process.env, { shortcut: WIN.shortcut, target: WIN.exe, workdir: HOME })
349
+ try {
350
+ execFileSync(sc.command, sc.args, { env: sc.env, stdio: ['ignore', 'ignore', 'inherit'], windowsHide: true })
351
+ } catch (e) {
352
+ console.log(`Installed: ${WIN.dir}`)
353
+ console.error(`Could not create the Start menu shortcut (${e.message}). Start ${WIN.exe} directly, or run \`centralu\`.`)
354
+ process.exit(1)
355
+ }
356
+ console.log(`Installed: ${WIN.dir}`)
357
+ console.log(`Start menu: ${WIN.shortcut}`)
358
+ console.log('It can now be found in Start and Windows search, and `centralu` starts this copy too.')
90
359
  }
91
360
 
92
361
  function uninstall() {
93
- if (!existsSync(INSTALLED)) {
94
- console.log(`${INSTALLED}가 없습니다 — 지울 것이 없습니다.`)
362
+ const paths = installedPaths(PLATFORM, process.env, HOME)
363
+ const present = paths.filter((p) => existsSync(p))
364
+ if (present.length === 0) {
365
+ console.log(`${paths[0]} does not exist — nothing to remove.`)
95
366
  return
96
367
  }
97
- rmSync(INSTALLED, { recursive: true, force: true })
98
- console.log(`지웠습니다: ${INSTALLED}`)
99
- console.log('패키지 자체를 지우려면: npm uninstall -g centralu')
100
- console.log(`대화 기록은 그대로 남아 있습니다 (~/.control-center). 지우려면 직접 지우세요.`)
368
+ for (const installed of present) {
369
+ try {
370
+ rmSync(installed, { recursive: true, force: true })
371
+ } catch (e) {
372
+ if (PLATFORM !== 'win32' || !isBusyError(e)) throw e
373
+ console.error(busyMessage(installed))
374
+ process.exit(1)
375
+ }
376
+ console.log(`Removed: ${installed}`)
377
+ }
378
+ console.log('To remove the package itself: npm uninstall -g centralu')
379
+ const data = PLATFORM === 'win32' ? '%USERPROFILE%\\.centralu' : '~/.centralu'
380
+ console.log(`Conversation history is left in place (${data}). Remove it yourself if you want to.`)
101
381
  }
102
382
 
103
383
  /**
104
- * npm 레지스트리가 곧 업데이트 채널이다 — 서버도 서명 키도 따로 필요 없다.
384
+ * The npm registry itself is the update channel — no separate server or signing key needed.
105
385
  *
106
- * 실패를 뭉뚱그리지 않는다. 못 닿은 것(네트워크)과 없는 것(404)은 **사용자가 할 일이 다르다** —
107
- * 앞은 연결을 보라는 말이고, 뒤는 봐도 소용없다는 말이다.
386
+ * Failures are not lumped together. Being unreachable (network) and not existing (404) call
387
+ * for **different actions from the person** — the first says to check the connection, the
388
+ * second says checking will not help.
108
389
  */
109
390
  async function latestVersion(timeoutMs = 2000) {
110
391
  try {
@@ -117,68 +398,130 @@ async function latestVersion(timeoutMs = 2000) {
117
398
  const version = body?.version
118
399
  return typeof version === 'string' ? { ok: true, version } : { ok: false, reason: 'bad-response' }
119
400
  } catch {
120
- return { ok: false, reason: 'network' } // 네트워크가 없어도 앱은 떠야 한다
401
+ return { ok: false, reason: 'network' } // The app has to launch even with no network.
121
402
  }
122
403
  }
123
404
 
124
- /** `1.2.10` > `1.2.9` — 문자열 비교로는 틀린다 */
125
- function isNewer(a, b) {
126
- const pa = String(a).split('.').map(Number)
127
- const pb = String(b).split('.').map(Number)
128
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
129
- const x = pa[i] ?? 0
130
- const y = pb[i] ?? 0
131
- if (x !== y) return x > y
132
- }
133
- return false
134
- }
135
405
 
136
406
  async function update() {
137
407
  const res = await latestVersion(8000)
138
408
  if (!res.ok) {
139
409
  if (res.reason === 'missing') {
140
- console.error(`레지스트리에 ${pkg.name}가 없습니다. 이름이 바뀌었거나 아직 발행 전입니다.`)
141
- console.error('https://github.com/ijun17/centralu/releases 를 확인해 주세요.')
410
+ console.error(`${pkg.name} is not on the registry. The name may have changed, or it has not been published yet.`)
411
+ console.error('Please check https://github.com/ijun17/centralu/releases.')
142
412
  } else if (res.reason === 'network') {
143
- console.error('레지스트리에 닿지 못했습니다. 네트워크를 확인하고 다시 시도해 주세요.')
413
+ console.error('Could not reach the registry. Please check your network and try again.')
144
414
  } else {
145
- console.error(`레지스트리가 예상 밖의 응답을 했습니다 (${res.reason}).`)
415
+ console.error(`The registry gave an unexpected response (${res.reason}).`)
146
416
  }
147
417
  process.exit(1)
148
418
  }
149
419
  const latest = res.version
150
420
  if (!isNewer(latest, pkg.version)) {
151
- console.log(`이미 최신입니다 (${pkg.version}).`)
421
+ console.log(`Already up to date (${pkg.version}).`)
422
+ // The package can be up to date while the copy is not — that is exactly the state of
423
+ // someone who upgraded with `npm i -g`.
424
+ notifyIfCopyStale()
152
425
  return
153
426
  }
154
- console.log(`${pkg.version} → ${latest} 로 올립니다.`)
155
- execFileSync('npm', ['i', '-g', `${pkg.name}@${latest}`], { stdio: 'inherit' })
156
- // /Applications에 넣어둔 사람은 그쪽도 함께 갱신해야 옛 버전이 남지 않는다
157
- if (existsSync(INSTALLED)) {
158
- console.log(`${INSTALLED}도 갱신합니다.`)
159
- execFileSync(process.argv[1], ['install'], { stdio: 'inherit' })
427
+ console.log(`Upgrading ${pkg.version} → ${latest}.`)
428
+ const npm = npmCommand(PLATFORM, ['i', '-g', `${pkg.name}@${latest}`])
429
+ try {
430
+ execFileSync(npm.command, npm.args, npm.options)
431
+ } catch (e) {
432
+ // On Windows the usual cause is the app running from inside the package: its files are
433
+ // locked, and npm cannot replace them. npm's own output (above) has the details.
434
+ if (PLATFORM === 'win32') console.error(`\n${busyMessage('the npm package')}`)
435
+ process.exit(typeof e?.status === 'number' ? e.status : 1)
436
+ }
437
+ // Someone with a copy in /Applications (or %LOCALAPPDATA%\Programs) needs that updated
438
+ // too, or the old version stays behind.
439
+ // On Linux the menu entry points at the package instead of a copy, so rewriting it is
440
+ // cheap — but it is still worth doing, because the Exec path is what would go stale.
441
+ //
442
+ // The *new* launcher does the refresh: this file has just been replaced on disk. It is
443
+ // run through `node` rather than as a script, because Windows cannot execute a `.mjs`.
444
+ const installed = installedPaths(PLATFORM, process.env, HOME)[0]
445
+ if (existsSync(installed)) {
446
+ console.log(`Updating ${installed} too.`)
447
+ execFileSync(process.execPath, [process.argv[1], 'install'], { stdio: 'inherit' })
160
448
  }
161
- console.log('끝났습니다. 앱이 떠 있다면 다시 시작해 주세요.')
449
+ console.log('Done. If the app is open, please restart it.')
162
450
  }
163
451
 
164
- /** 앱을 띄운 뒤에만 알린다 — 업데이트 확인 때문에 실행이 늦어지면 안 된다 */
452
+ /**
453
+ * The version of the copy placed in /Applications. null if there is nothing to compare.
454
+ *
455
+ * `defaults` is used because there is no guarantee Info.plist stays XML — Tauri just happens
456
+ * to write it as XML today, and if it ever switches to a binary plist, anything reading it
457
+ * with a regex would silently stop working. `defaults` is always present on a Mac and reads
458
+ * both formats.
459
+ *
460
+ * On Windows it is the file `centralu install` wrote beside the copy (see `windowsInstall`
461
+ * for why not the exe's own version).
462
+ */
463
+ function installedCopyVersion() {
464
+ if (PLATFORM === 'win32') {
465
+ try {
466
+ return readFileSync(WIN.versionFile, 'utf8').trim()
467
+ } catch {
468
+ return null
469
+ }
470
+ }
471
+ if (PLATFORM !== 'darwin' || !existsSync(INSTALLED)) return null
472
+ try {
473
+ const out = execFileSync('/usr/bin/defaults', ['read', join(INSTALLED, 'Contents/Info.plist'), 'CFBundleShortVersionString'], {
474
+ encoding: 'utf8',
475
+ stdio: ['ignore', 'pipe', 'ignore'],
476
+ })
477
+ return out.trim()
478
+ } catch {
479
+ // Failing to read this is not worth mentioning — the app has already launched, and there
480
+ // is nothing useful to say here.
481
+ return null
482
+ }
483
+ }
484
+
485
+ /**
486
+ * One line, if the package and the /Applications copy have drifted apart.
487
+ *
488
+ * `npm i -g centralu` only changes the package. So a state quietly forms where the launcher is
489
+ * new but the app that opens from Spotlight is old — this actually happened (beta.1 stayed in
490
+ * /Applications while only the package moved to beta.3), and nothing on screen said so.
491
+ *
492
+ * **Says it, does not do it.** The same rule as the in-app update line. Overwriting someone's
493
+ * /Applications without asking is the exact reason this package keeps `install` as a separate
494
+ * step.
495
+ */
496
+ function notifyIfCopyStale() {
497
+ const version = installedCopyVersion()
498
+ if (!copyDiffers(pkg.version, version)) return
499
+ const where = PLATFORM === 'win32' ? WIN.dir : '/Applications'
500
+ console.log(`\nThe ${where} copy is ${version} (this package is ${pkg.version}).\n centralu install`)
501
+ }
502
+
503
+ /** Only announced after the app has launched — checking for updates must never delay startup. */
165
504
  async function notifyIfOutdated() {
166
- // 여기서는 실패를 **전부 삼킨다.** 앱을 띄우러 온 사람에게 레지스트리 사정을 말할 이유가 없다
505
+ // Every failure here is **swallowed entirely.** Someone who came here to launch the app has
506
+ // no reason to be told about registry troubles.
167
507
  const res = await latestVersion()
168
508
  if (res.ok && isNewer(res.version, pkg.version)) {
169
- console.log(`\n새 버전이 있습니다: ${pkg.version} → ${res.version}\n centralu update`)
509
+ console.log(`\nA new version is available: ${pkg.version} → ${res.version}\n centralu update`)
170
510
  }
171
511
  }
172
512
 
173
513
  const HELP = `${APP_NAME} ${pkg.version}
174
514
 
175
- centralu 앱을 실행합니다
176
- centralu install /Applications에 복사합니다 (Launchpad·Spotlight에 뜨게)
177
- centralu uninstall /Applications에서 지웁니다 (대화 기록은 남습니다)
178
- centralu update 새 버전이 있으면 올립니다
179
- centralu --version 버전을 출력합니다
515
+ centralu Launches the app
516
+ centralu install Registers it in the app list (macOS: /Applications, Linux: a menu entry,
517
+ Windows: %LOCALAPPDATA%\\Programs\\Centralu and a Start menu shortcut)
518
+ centralu uninstall Removes that registration (conversation history is kept)
519
+ centralu update Upgrades if a new version is available
520
+ centralu serve Runs the host alone on this machine, for the app on another computer
521
+ to reach over SSH (\`centralu serve --help\`)
522
+ centralu --version Prints the version
180
523
 
181
- 필요한 것: Node 22+, 그리고 claude 또는 codex CLI (앱 첫 화면이 상태를 알려줍니다)`
524
+ Requires: Node 22+, and the claude or codex CLI (the app's first screen reports the status)`
182
525
 
183
526
  const [cmd, ...rest] = process.argv.slice(2)
184
527
  switch (cmd) {
@@ -191,6 +534,33 @@ switch (cmd) {
191
534
  case 'update':
192
535
  await update()
193
536
  break
537
+ case 'serve': {
538
+ // No update notice here: `--connection`'s stdout is read by a program, and a foreground
539
+ // server's terminal is a log.
540
+ const args = parseServeArgs(rest)
541
+ if (args.error) {
542
+ console.error(args.error)
543
+ process.exit(2)
544
+ }
545
+ if (args.mode === 'help') {
546
+ console.log(SERVE_HELP)
547
+ break
548
+ }
549
+ try {
550
+ if (args.mode === 'rotate') {
551
+ process.exitCode = rotateToken({ env: process.env, home: HOME })
552
+ break
553
+ }
554
+ // realpath: npm's bin is a symlink to this file, and the launcher must not depend on the link
555
+ const opts = { env: process.env, home: HOME, entry: requireHostEntry(), version: pkg.version, cliPath: realpathSync(process.argv[1]) }
556
+ process.exitCode = args.mode === 'connection' ? await printConnection(opts) : await runServe({ ...opts, port: args.port })
557
+ } catch (e) {
558
+ // A state file that cannot be read or written: one sentence, not a stack, and nothing on stdout
559
+ console.error(`centralu serve: ${e?.message ?? e}`)
560
+ process.exitCode = 1
561
+ }
562
+ break
563
+ }
194
564
  case '--version':
195
565
  case '-v':
196
566
  console.log(pkg.version)
@@ -200,7 +570,10 @@ switch (cmd) {
200
570
  case 'help':
201
571
  console.log(HELP)
202
572
  break
203
- default:
204
- run(cmd ? [cmd, ...rest] : [])
205
- await notifyIfOutdated()
573
+ default: {
574
+ // Started before the update check, never after it: the check must not delay startup.
575
+ const launched = run(cmd ? [cmd, ...rest] : [])
576
+ notifyIfCopyStale()
577
+ await Promise.all([launched, notifyIfOutdated()])
578
+ }
206
579
  }