moi-computer 0.5.2-next.1 → 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.
Files changed (83) hide show
  1. package/README.md +39 -0
  2. package/client/AGENTS.md +9 -0
  3. package/client/api/app-ui-keys.ts +4 -0
  4. package/client/api/workspace-keys.ts +2 -2
  5. package/client/app/routes/WorkspaceRoute.tsx +8 -28
  6. package/client/components/shared/Composer.tsx +3 -6
  7. package/client/components/shared/IconGhost.tsx +130 -0
  8. package/client/components/ui/dropdown-menu.tsx +1 -1
  9. package/client/components/ui/spinner.tsx +18 -0
  10. package/client/components/ui/toast.tsx +220 -0
  11. package/client/features/chat/ChatComposer.tsx +3 -2
  12. package/client/features/chat/ChatPanel.tsx +7 -6
  13. package/client/features/chat/ChatPopup.tsx +10 -4
  14. package/client/features/chat/ChatSelector.tsx +263 -48
  15. package/client/features/chat/ModelPicker.tsx +13 -18
  16. package/client/features/chat/api.ts +36 -9
  17. package/client/features/chat/chat-frames.ts +35 -6
  18. package/client/features/chat/chat-send.ts +25 -1
  19. package/client/features/chat/chat-store.ts +43 -18
  20. package/client/features/chat/useChat.ts +54 -52
  21. package/client/features/chat/useSelectedSession.ts +151 -0
  22. package/client/features/chat/useStickToBottom.ts +3 -3
  23. package/client/features/home/api.ts +0 -2
  24. package/client/features/scratchpad/ScratchpadControls.tsx +2 -2
  25. package/client/features/settings/WorkspaceSettings.tsx +6 -6
  26. package/client/features/views/ViewBuilderTab.tsx +3 -4
  27. package/client/features/views/useViewBuilderActions.ts +3 -1
  28. package/client/features/workspace/WorkspaceScreen.tsx +38 -17
  29. package/client/features/workspace/WorkspaceTabs.tsx +10 -1
  30. package/client/main.tsx +2 -0
  31. package/client/runtime/useWorkspaceEvents.ts +1 -0
  32. package/client/store/ui.ts +2 -2
  33. package/dist/{chunk-zs4mte79.js → chunk-0pcdwjkp.js} +1 -1
  34. package/dist/chunk-175bm057.js +27 -0
  35. package/dist/chunk-55sh4dty.js +2 -0
  36. package/dist/{chunk-tzz101ea.js → chunk-9y2zbzqz.js} +1 -1
  37. package/dist/{chunk-jvhvme3z.js → chunk-afgbg75t.js} +1 -1
  38. package/dist/chunk-agtetn7n.css +1 -0
  39. package/dist/chunk-dfs36zgc.js +1 -0
  40. package/dist/chunk-exj6hr30.js +9 -0
  41. package/dist/{chunk-bcrkdhwe.js → chunk-m11ckkxd.js} +1 -1
  42. package/dist/{chunk-kfw1qwqe.js → chunk-rxvx4ta9.js} +3 -3
  43. package/dist/{chunk-xwhya7kb.js → chunk-w3tnv51j.js} +1 -1
  44. package/dist/index.html +1 -1
  45. package/lib/attachment-note.ts +18 -0
  46. package/lib/chat-title.ts +6 -0
  47. package/lib/types.ts +24 -10
  48. package/package.json +1 -1
  49. package/server/agent-caller.ts +16 -0
  50. package/server/api.ts +90 -9
  51. package/server/app-settings.ts +1 -1
  52. package/server/cli.ts +628 -45
  53. package/server/control.ts +18 -1
  54. package/server/data-dir.ts +1 -1
  55. package/server/harness/README.md +6 -0
  56. package/server/harness/claude-code/adapter.ts +2 -2
  57. package/server/harness/claude-code/index.ts +7 -1
  58. package/server/harness/claude-code/session-title.ts +106 -0
  59. package/server/harness/claude-code/session.ts +107 -17
  60. package/server/harness/claude-code/sessions.ts +63 -4
  61. package/server/harness/codex/client.ts +33 -13
  62. package/server/harness/codex/index.ts +2 -0
  63. package/server/harness/codex/session-title.ts +149 -0
  64. package/server/harness/codex/session.ts +84 -11
  65. package/server/harness/openclaw/adapter.ts +4 -2
  66. package/server/harness/openclaw/discovery.ts +2 -0
  67. package/server/harness/openclaw/session.ts +15 -7
  68. package/server/harness/session-title.ts +96 -0
  69. package/server/harness/types.ts +2 -0
  70. package/server/selected-session.ts +132 -0
  71. package/server/service.ts +786 -0
  72. package/server/{thread-config.ts → session-config.ts} +57 -39
  73. package/server/status.ts +2 -0
  74. package/server/update.ts +141 -0
  75. package/server/version.ts +41 -0
  76. package/server/web.ts +17 -1
  77. package/workspace/.claude/skills/moi-workspace/DESIGN.md +16 -26
  78. package/workspace/.claude/skills/moi-workspace/SKILL.md +8 -2
  79. package/dist/chunk-94m3q9ce.js +0 -1
  80. package/dist/chunk-k9dcnd73.js +0 -27
  81. package/dist/chunk-pk11vfzs.js +0 -9
  82. package/dist/chunk-r2bqaege.js +0 -2
  83. package/dist/chunk-y4g8j7mv.css +0 -1
package/server/cli.ts CHANGED
@@ -2,11 +2,13 @@
2
2
  import './cli-colors' // must precede citty: sets NO_COLOR before its color flag is computed
3
3
  import { defineCommand, runMain, showUsage } from 'citty'
4
4
  import { parse as devalueParse } from 'devalue'
5
- import { existsSync, readFileSync } from 'node:fs'
5
+ import { existsSync } from 'node:fs'
6
6
  import { tmpdir } from 'node:os'
7
7
  import { join, resolve } from 'path'
8
8
  import pc from './cli-pc'
9
9
 
10
+ import { isAgentCaller } from './agent-caller'
11
+
10
12
  import { COLOR_THEMES, FONT_THEMES, deriveThemeColors } from '@/lib/themes'
11
13
  import type { ColorTheme, FontTheme } from '@/lib/themes'
12
14
  import { isParamsRecord } from '@/lib/workspace-tabs'
@@ -43,6 +45,26 @@ import {
43
45
  staleSkillNotice
44
46
  } from './skill-version'
45
47
  import { updateWorkspaceSkills } from './skill-update'
48
+ import {
49
+ ServiceError,
50
+ analyzeInstall,
51
+ installService,
52
+ queryServerInfo,
53
+ restartService,
54
+ serviceLogPath,
55
+ serviceStatus,
56
+ uninstallService
57
+ } from './service'
58
+ import {
59
+ detectPackageManager,
60
+ fetchLatestVersion,
61
+ installedBinVersion,
62
+ isNewer,
63
+ manualUpdateLines,
64
+ runPackageManager,
65
+ updateArgv
66
+ } from './update'
67
+ import { VERSION, isPrerelease, versionWithCommit } from './version'
46
68
  import {
47
69
  getWorkspaceEnvView,
48
70
  isValidEnvKey,
@@ -344,9 +366,26 @@ const start = defineCommand({
344
366
  // server. Skipped when MOI_SERVER=1 (we are the spawned server itself).
345
367
  if (!process.env.MOI_SERVER) {
346
368
  if (await isServerRunning()) {
347
- console.log(
348
- '\n' + pc.yellow('◆') + ' Server is already running on http://localhost:' + PORT + '\n'
349
- )
369
+ // Say who owns the running server: a service-managed one is expected
370
+ // to be here, and `moi service` is how to manage it.
371
+ const info = await queryServerInfo()
372
+ const port = info?.port || PORT
373
+ if (info?.service) {
374
+ console.log(
375
+ '\n' +
376
+ pc.yellow('◆') +
377
+ ' The moi service is already running on http://localhost:' +
378
+ port +
379
+ pc.dim(` (v${info.version})`) +
380
+ '\n' +
381
+ pc.dim(' Manage it with `moi service` — restart, logs, uninstall.') +
382
+ '\n'
383
+ )
384
+ } else {
385
+ console.log(
386
+ '\n' + pc.yellow('◆') + ' Server is already running on http://localhost:' + port + '\n'
387
+ )
388
+ }
350
389
  process.exit(0)
351
390
  }
352
391
 
@@ -378,7 +417,28 @@ const start = defineCommand({
378
417
  // This IS the server process (MOI_SERVER=1). cwd is the package root when the
379
418
  // dev bundler runs (bunfig loaded at Bun startup) or a neutral dir for a
380
419
  // prebuilt install — see serverCwd().
381
- await import('./web')
420
+ try {
421
+ await import('./web')
422
+ } catch (err) {
423
+ // Startup failure (port taken, config error). Under the service manager
424
+ // exit 0 on purpose: launchd (KeepAlive.SuccessfulExit=false) and
425
+ // systemd (Restart=on-failure) both read a clean exit as "do not
426
+ // respawn", so a permanently-broken start idles instead of looping.
427
+ const code = (err as { code?: string })?.code
428
+ if (code === 'EADDRINUSE') {
429
+ console.error(
430
+ `\n${pc.red('✗')} Port already in use (http :${PORT} / control :${CONTROL_PORT}) — ` +
431
+ 'is another moi server running?'
432
+ )
433
+ } else {
434
+ console.error(`\n${pc.red('✗')} Server failed to start: ${String(err)}`)
435
+ }
436
+ if (process.env.MOI_SERVICE) {
437
+ console.error(pc.dim(' The service stays idle — fix this, then `moi service restart`.\n'))
438
+ process.exit(0)
439
+ }
440
+ process.exit(1)
441
+ }
382
442
  console.log(`\n${pc.green('✓')} Server started on http://localhost:${PORT}`)
383
443
  console.log(pc.dim(' Press Ctrl+C to stop\n'))
384
444
  // Stay alive as the server
@@ -750,6 +810,20 @@ const theme = defineCommand({
750
810
  }
751
811
  })
752
812
 
813
+ // The CLI-vs-server freshness check, shared by `moi status` and `moi update`:
814
+ // compares this CLI's version against what the running server reports over the
815
+ // control port. Works no matter how the upgrade happened (`moi update` or a
816
+ // manual package-manager install) — the comparison reads live state, it does
817
+ // not live inside the update command.
818
+ function versionMismatchNotice(serverVersion: string): string | null {
819
+ if (serverVersion === VERSION) return null
820
+ return (
821
+ pc.yellow('⚠') +
822
+ ` Server is running v${serverVersion}, this CLI is v${VERSION}.\n` +
823
+ pc.dim(' Restart to match: `moi service restart` (service) or Ctrl-C + `moi start`.')
824
+ )
825
+ }
826
+
753
827
  const status = defineCommand({
754
828
  meta: { name: 'status', description: 'Show server status and registered workspaces' },
755
829
  async run() {
@@ -757,17 +831,32 @@ const status = defineCommand({
757
831
  const notice = await staleSkillNotice(process.cwd())
758
832
 
759
833
  if (!running) {
760
- console.log('\n' + pc.dim('○') + ' Server is ' + pc.bold('not running') + '\n')
834
+ console.log('\n' + pc.dim('○') + ' Server is ' + pc.bold('not running'))
835
+ console.log(pc.dim(` cli version ${VERSION}`) + '\n')
761
836
  process.exit(0)
762
837
  }
763
838
 
839
+ const info = await queryServerInfo()
764
840
  console.log(
765
841
  '\n' +
766
842
  pc.green('●') +
767
843
  ' Server is ' +
768
844
  pc.bold('running') +
769
- pc.dim(` (http port: ${PORT}, control port: ${CONTROL_PORT})`)
845
+ pc.dim(
846
+ ` (http port: ${info?.port || PORT}, control port: ${CONTROL_PORT}` +
847
+ (info?.pid ? `, pid: ${info.pid}` : '') +
848
+ ')'
849
+ )
770
850
  )
851
+ if (info) {
852
+ console.log(
853
+ pc.dim(` server version ${info.version}`) +
854
+ (info.service ? pc.dim(' · service-managed (`moi service`)') : '')
855
+ )
856
+ }
857
+ console.log(pc.dim(` cli version ${VERSION}`))
858
+ const mismatch = info ? versionMismatchNotice(info.version) : null
859
+ if (mismatch) console.log('\n' + mismatch)
771
860
 
772
861
  await new Promise<void>((resolve, reject) => {
773
862
  const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
@@ -2050,61 +2139,555 @@ const skill = defineCommand({
2050
2139
  }
2051
2140
  })
2052
2141
 
2053
- // `<package version> (<8-char commit>)`, e.g. `0.1.3 (27e17e80)`. The commit is
2054
- // read from git at call time, so it appears for a source/`bun link` checkout and
2055
- // is simply omitted for a published package (which ships no .git).
2056
- function moiVersion(): string {
2057
- const root = join(import.meta.dir, '..')
2058
- let version = '0.0.0'
2059
- try {
2060
- version = (JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { version: string })
2061
- .version
2062
- } catch {}
2063
- let commit = ''
2142
+ // ---- service ----------------------------------------------------------------
2143
+
2144
+ function serviceFail(err: unknown): never {
2145
+ const message = err instanceof ServiceError ? err.message : String(err)
2146
+ console.error('\n' + pc.red('✗') + ' ' + message + '\n')
2147
+ process.exit(1)
2148
+ }
2149
+
2150
+ // Shared success line after install/restart: did the server actually come up,
2151
+ // and on which version?
2152
+ function printServiceServer(info: Awaited<ReturnType<typeof queryServerInfo>>) {
2153
+ if (info) {
2154
+ console.log(
2155
+ ' server ' +
2156
+ pc.bold(`v${info.version}`) +
2157
+ ` running on http://localhost:${info.port}` +
2158
+ pc.dim(` (pid ${info.pid})`)
2159
+ )
2160
+ const mismatch = versionMismatchNotice(info.version)
2161
+ if (mismatch) console.log('\n' + mismatch)
2162
+ } else {
2163
+ console.log(
2164
+ ' ' +
2165
+ pc.yellow('server did not come up — check `moi service logs`') +
2166
+ pc.dim(' (it may still be starting)')
2167
+ )
2168
+ }
2169
+ }
2170
+
2171
+ const serviceInstall = defineCommand({
2172
+ meta: {
2173
+ name: 'install',
2174
+ description: 'Install and start the user service (launchd on macOS, systemd on Linux)'
2175
+ },
2176
+ args: {
2177
+ port: { type: 'string', description: 'HTTP port for the service server (default: 13337)' },
2178
+ env: {
2179
+ type: 'string',
2180
+ description:
2181
+ 'Extra env var names to capture from this shell, comma-separated (e.g. --env MY_TOKEN,OTHER)'
2182
+ }
2183
+ },
2184
+ async run({ args }) {
2185
+ // Check the install shape first: telling someone to stop their server only
2186
+ // to then refuse the checkout would be a pointless round-trip.
2187
+ const analysis = analyzeInstall()
2188
+ if (analysis.kind !== 'global') {
2189
+ try {
2190
+ await installService() // throws the precise refusal for this analysis
2191
+ } catch (err) {
2192
+ serviceFail(err)
2193
+ }
2194
+ }
2195
+ // A foreground `moi start` holds the same ports the service needs. Refuse
2196
+ // rather than install a unit that instantly fails on bind.
2197
+ const runningInfo = await queryServerInfo()
2198
+ const foreground = (await isServerRunning()) && !runningInfo?.service
2199
+ if (foreground) {
2200
+ serviceFail(
2201
+ new ServiceError(
2202
+ 'A foreground server is running' +
2203
+ (runningInfo?.pid ? ` (pid ${runningInfo.pid})` : '') +
2204
+ '.\n Stop it (Ctrl-C in its terminal), then rerun `moi service install`.'
2205
+ )
2206
+ )
2207
+ }
2208
+ const port = args.port ? Number(args.port) : undefined
2209
+ if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535)) {
2210
+ serviceFail(new ServiceError(`Invalid --port value "${args.port}" — use a port number.`))
2211
+ }
2212
+ // citty hands back an array when the flag repeats — accept both shapes.
2213
+ const envArg = Array.isArray(args.env) ? args.env.join(',') : args.env
2214
+ const extraEnv = (envArg ?? '')
2215
+ .split(',')
2216
+ .map(k => k.trim())
2217
+ .filter(Boolean)
2218
+ try {
2219
+ const result = await installService({ port, extraEnv })
2220
+ console.log(
2221
+ '\n' +
2222
+ pc.green('✓') +
2223
+ ' Service installed ' +
2224
+ pc.dim(`(${process.platform === 'darwin' ? 'launchd' : 'systemd user unit'})`)
2225
+ )
2226
+ console.log(' unit ' + pc.dim(tildifyPath(result.unitPath)))
2227
+ if (result.logPath) console.log(' logs ' + pc.dim(tildifyPath(result.logPath)))
2228
+ printServiceServer(result.info)
2229
+ console.log(pc.dim('\n Starts on login, restarts on crash, survives reboots.'))
2230
+ for (const note of result.notes) console.log(pc.yellow(' ' + note))
2231
+ console.log()
2232
+ } catch (err) {
2233
+ serviceFail(err)
2234
+ }
2235
+ }
2236
+ })
2237
+
2238
+ const serviceUninstall = defineCommand({
2239
+ meta: { name: 'uninstall', description: 'Stop the service and remove its unit' },
2240
+ async run() {
2241
+ try {
2242
+ const { unitPath, existed } = await uninstallService()
2243
+ if (!existed) {
2244
+ console.log(
2245
+ '\n' +
2246
+ pc.dim('○') +
2247
+ ' Service is not installed ' +
2248
+ pc.dim(`(${tildifyPath(unitPath)})`) +
2249
+ '\n'
2250
+ )
2251
+ return
2252
+ }
2253
+ console.log(
2254
+ '\n' + pc.green('✓') + ' Service removed ' + pc.dim(`(${tildifyPath(unitPath)})`) + '\n'
2255
+ )
2256
+ } catch (err) {
2257
+ serviceFail(err)
2258
+ }
2259
+ }
2260
+ })
2261
+
2262
+ const serviceRestart = defineCommand({
2263
+ meta: { name: 'restart', description: 'Restart the service server' },
2264
+ async run() {
2265
+ try {
2266
+ const info = await restartService()
2267
+ console.log('\n' + pc.green('✓') + ' Service restarted')
2268
+ printServiceServer(info)
2269
+ console.log()
2270
+ } catch (err) {
2271
+ serviceFail(err)
2272
+ }
2273
+ }
2274
+ })
2275
+
2276
+ const serviceLogs = defineCommand({
2277
+ meta: { name: 'logs', description: 'Show server logs (journalctl on Linux, log file on macOS)' },
2278
+ args: {
2279
+ lines: { type: 'string', default: '80', description: 'How many trailing lines to show' },
2280
+ follow: {
2281
+ type: 'boolean',
2282
+ alias: 'f',
2283
+ default: false,
2284
+ description: 'Keep following new output'
2285
+ }
2286
+ },
2287
+ async run({ args }) {
2288
+ const n = Math.max(1, Number(args.lines) || 80)
2289
+ if (process.platform === 'linux') {
2290
+ // journald owns the log (bounded, rotated). Inherit stdio so -f streams.
2291
+ const argv = ['journalctl', '--user', '-u', 'moi.service', '-n', String(n), '--no-pager']
2292
+ if (args.follow) argv.push('-f')
2293
+ const proc = Bun.spawn(argv, { stdin: 'inherit', stdout: 'inherit', stderr: 'inherit' })
2294
+ process.exit(await proc.exited)
2295
+ }
2296
+ const logPath = serviceLogPath()
2297
+ if (!existsSync(logPath)) {
2298
+ console.log('\n' + pc.dim('○') + ' No logs yet ' + pc.dim(`(${tildifyPath(logPath)})`) + '\n')
2299
+ process.exit(0)
2300
+ }
2301
+ console.error(pc.dim(tildifyPath(logPath)))
2302
+ const proc = Bun.spawn(['tail', '-n', String(n), ...(args.follow ? ['-F'] : []), logPath], {
2303
+ stdin: 'inherit',
2304
+ stdout: 'inherit',
2305
+ stderr: 'inherit'
2306
+ })
2307
+ process.exit(await proc.exited)
2308
+ }
2309
+ })
2310
+
2311
+ function tildifyPath(p: string): string {
2312
+ const home = process.env.HOME
2313
+ return home && p.startsWith(home) ? '~' + p.slice(home.length) : p
2314
+ }
2315
+
2316
+ async function runServiceStatus() {
2064
2317
  try {
2065
- const out = Bun.spawnSync(['git', 'rev-parse', '--short=8', 'HEAD'], { cwd: root })
2066
- if (out.success) commit = out.stdout.toString().trim()
2067
- } catch {}
2068
- return commit ? `${version} (${commit})` : version
2318
+ const s = await serviceStatus()
2319
+ const flavor = s.platform === 'darwin' ? 'launchd user agent' : 'systemd user unit'
2320
+ console.log('\n' + pc.bold('moi service') + pc.dim(` — ${flavor}`))
2321
+ console.log()
2322
+ if (!s.installed) {
2323
+ console.log(' ' + pc.dim('○') + ' Not installed')
2324
+ console.log(
2325
+ pc.dim(' Run `moi service install` to start moi on login and keep it running.')
2326
+ )
2327
+ console.log()
2328
+ process.exit(0)
2329
+ }
2330
+ const rt = s.runtime
2331
+ const stateLabel =
2332
+ rt === null
2333
+ ? pc.dim('unknown')
2334
+ : rt.state === 'running'
2335
+ ? pc.green('● running') + (rt.pid ? pc.dim(` (pid ${rt.pid})`) : '')
2336
+ : rt.state === 'failed'
2337
+ ? pc.red('✗ failed') + pc.dim(rt.detail ? ` (${rt.detail})` : '')
2338
+ : rt.state === 'unavailable'
2339
+ ? pc.yellow('? unavailable') + pc.dim(rt.detail ? ` — ${rt.detail}` : '')
2340
+ : pc.dim('○ ' + rt.state)
2341
+ console.log(' state ' + stateLabel)
2342
+ console.log(' unit ' + pc.dim(tildifyPath(s.unitPath)))
2343
+ if (s.logPath)
2344
+ console.log(' logs ' + pc.dim(tildifyPath(s.logPath)) + pc.dim(' (`moi service logs`)'))
2345
+ else
2346
+ console.log(' logs ' + pc.dim('journalctl --user -u moi.service (`moi service logs`)'))
2347
+ const info = await queryServerInfo()
2348
+ if (info) {
2349
+ console.log(
2350
+ ' server ' +
2351
+ pc.bold(`v${info.version}`) +
2352
+ pc.dim(` on http://localhost:${info.port} (pid ${info.pid})`)
2353
+ )
2354
+ if (!info.service) {
2355
+ console.log(
2356
+ pc.yellow(' ⚠ The running server is a foreground `moi start`, not the service.')
2357
+ )
2358
+ }
2359
+ } else if (rt?.state === 'running') {
2360
+ console.log(' server ' + pc.yellow('unreachable on the control port'))
2361
+ }
2362
+ console.log()
2363
+ if (s.binMissing && s.bin) {
2364
+ console.log(
2365
+ pc.yellow(` ⚠ The service execs ${s.bin}, which no longer exists`) +
2366
+ pc.dim(' (moi moved or was reinstalled elsewhere).') +
2367
+ '\n' +
2368
+ pc.dim(' Rerun `moi service install` to re-capture paths.')
2369
+ )
2370
+ }
2371
+ if (s.bunMissing) {
2372
+ console.log(
2373
+ pc.yellow(' ⚠ No bun on the service PATH — the server cannot start.') +
2374
+ '\n' +
2375
+ pc.dim(' Reinstall bun, then rerun `moi service install`.')
2376
+ )
2377
+ }
2378
+ if (s.linger === 'disabled') {
2379
+ console.log(
2380
+ pc.yellow(' ⚠ Lingering is off — the service stops when your last session ends.') +
2381
+ '\n' +
2382
+ pc.dim(' Enable: loginctl enable-linger')
2383
+ )
2384
+ }
2385
+ const mismatch = info ? versionMismatchNotice(info.version) : null
2386
+ if (mismatch) console.log(mismatch.replace(/^/gm, ' ').replace(/^ {2}⚠/, ' ⚠') + '\n')
2387
+ process.exit(0)
2388
+ } catch (err) {
2389
+ serviceFail(err)
2390
+ }
2391
+ }
2392
+
2393
+ const serviceSubCommands = {
2394
+ install: serviceInstall,
2395
+ uninstall: serviceUninstall,
2396
+ restart: serviceRestart,
2397
+ logs: serviceLogs
2398
+ }
2399
+
2400
+ const service = defineCommand({
2401
+ meta: {
2402
+ name: 'service',
2403
+ description: 'Run moi as a user service: `moi service install|uninstall|restart|logs`'
2404
+ },
2405
+ subCommands: serviceSubCommands,
2406
+ async run({ rawArgs }) {
2407
+ // citty invokes the parent run even after dispatching a subcommand — only
2408
+ // show status when none ran (same pattern as `moi env` / `moi tab`).
2409
+ const sub = rawArgs.find(a => !a.startsWith('-'))
2410
+ if (sub && Object.hasOwn(serviceSubCommands, sub)) return
2411
+ await runServiceStatus()
2412
+ }
2413
+ })
2414
+
2415
+ // ---- update -----------------------------------------------------------------
2416
+
2417
+ const update = defineCommand({
2418
+ meta: {
2419
+ name: 'update',
2420
+ description: 'Update moi to the latest published version'
2421
+ },
2422
+ args: {
2423
+ check: {
2424
+ type: 'boolean',
2425
+ default: false,
2426
+ description:
2427
+ 'Only check the registry, change nothing. Exit 0: up to date (or nothing to update), 1: update available, 2: check failed.'
2428
+ }
2429
+ },
2430
+ async run({ args }) {
2431
+ // A checkout has no owning package manager — updating means `git pull`.
2432
+ const analysis = analyzeInstall()
2433
+ if (analysis.kind === 'checkout') {
2434
+ console.log(
2435
+ '\n' +
2436
+ pc.yellow('◆') +
2437
+ ` This moi runs from a source tree (${analysis.reason}) — update it with git instead.\n`
2438
+ )
2439
+ process.exit(0)
2440
+ }
2441
+
2442
+ console.log('\n' + pc.bold('moi update') + pc.dim(` — installed v${VERSION}`))
2443
+
2444
+ if (isPrerelease(VERSION)) {
2445
+ console.log(
2446
+ '\n' +
2447
+ pc.yellow('◆') +
2448
+ ' Prerelease installs are updated manually — pick the tag you want:\n' +
2449
+ pc.dim(' bun i -g moi-computer@next (or @latest to leave the prerelease)\n')
2450
+ )
2451
+ process.exit(0)
2452
+ }
2453
+
2454
+ let latest: string
2455
+ try {
2456
+ latest = await fetchLatestVersion()
2457
+ } catch (err) {
2458
+ console.error(
2459
+ '\n' + pc.red('✗') + ' ' + (err instanceof Error ? err.message : String(err)) + '\n'
2460
+ )
2461
+ // Under --check, exit 2 keeps "check failed" distinct from "update
2462
+ // available" (exit 1) for scripts and agents.
2463
+ process.exit(args.check ? 2 : 1)
2464
+ }
2465
+
2466
+ if (!isNewer(latest, VERSION)) {
2467
+ console.log(pc.green('✓') + ` Already up to date (latest is v${latest})`)
2468
+ // --check is side-effect-free: skip the server sync, which can restart
2469
+ // a lagging service. `moi status` reports that lag without acting on it.
2470
+ if (!args.check) await reportServerFreshness()
2471
+ process.exit(0)
2472
+ }
2473
+
2474
+ if (args.check) {
2475
+ console.log(
2476
+ ` update available: ${pc.bold('v' + latest)}` + pc.dim(' — run `moi update` to install\n')
2477
+ )
2478
+ process.exit(1)
2479
+ }
2480
+
2481
+ console.log(` latest is ${pc.bold('v' + latest)} — updating`)
2482
+
2483
+ const pm = await detectPackageManager()
2484
+ if (!pm) {
2485
+ console.error(
2486
+ '\n' +
2487
+ pc.red('✗') +
2488
+ ' Could not tell which package manager owns this install' +
2489
+ pc.dim(` (${analysis.root})`) +
2490
+ '.\n Update it yourself with the one you installed moi with:\n' +
2491
+ manualUpdateLines(latest)
2492
+ .map(l => pc.dim(' ' + l))
2493
+ .join('\n') +
2494
+ '\n'
2495
+ )
2496
+ process.exit(1)
2497
+ }
2498
+
2499
+ const argv = updateArgv(pm, latest)
2500
+ console.log(pc.dim(` via ${pm}: ${argv.join(' ')}\n`))
2501
+ const code = await runPackageManager(argv)
2502
+ if (code !== 0) {
2503
+ console.error('\n' + pc.red('✗') + ` ${pm} exited with code ${code}.`)
2504
+ console.error(pc.dim(' Run it manually: ') + argv.join(' '))
2505
+ if (pm === 'npm') {
2506
+ console.error(
2507
+ pc.dim(
2508
+ ' If it failed with EACCES, your npm prefix is root-owned — fix ownership or use a user-level prefix.'
2509
+ )
2510
+ )
2511
+ }
2512
+ console.error()
2513
+ process.exit(1)
2514
+ }
2515
+
2516
+ // Trust but verify: ask the bin users actually run what version it is now.
2517
+ // A stale answer means the update landed somewhere PATH does not point.
2518
+ const binVersion = analysis.kind === 'global' ? await installedBinVersion(analysis.bin) : null
2519
+ if (binVersion === latest) {
2520
+ console.log('\n' + pc.green('✓') + ` moi updated to ${pc.bold('v' + latest)}`)
2521
+ } else if (binVersion) {
2522
+ console.log(
2523
+ '\n' +
2524
+ pc.yellow('⚠') +
2525
+ ` ${pm} finished, but \`moi\` on PATH reports v${binVersion} (expected v${latest}).` +
2526
+ '\n' +
2527
+ pc.dim(' Another install may shadow the updated one — check `which moi`.')
2528
+ )
2529
+ } else {
2530
+ console.log('\n' + pc.green('✓') + ` ${pm} finished (v${latest})`)
2531
+ }
2532
+
2533
+ await reportServerFreshness(latest)
2534
+ console.log()
2535
+ process.exit(0)
2536
+ }
2537
+ })
2538
+
2539
+ // After an update (or an up-to-date check), bring the running server along:
2540
+ // restart a service-managed one and verify the version it comes back with; a
2541
+ // foreground server in someone's terminal only ever gets a warning.
2542
+ async function reportServerFreshness(expected?: string) {
2543
+ const running = await isServerRunning()
2544
+ if (!running) return
2545
+ const info = await queryServerInfo()
2546
+ if (!info) {
2547
+ console.log(
2548
+ pc.yellow('⚠') +
2549
+ ' A server is running but too old to report its version — restart it to finish the update.'
2550
+ )
2551
+ return
2552
+ }
2553
+ const target = expected ?? VERSION
2554
+ if (info.version === target) {
2555
+ if (expected) console.log(pc.green('✓') + ` Server already on v${info.version}`)
2556
+ return
2557
+ }
2558
+ if (info.service) {
2559
+ console.log(pc.dim(` restarting the service (server was v${info.version})…`))
2560
+ try {
2561
+ const fresh = await restartService()
2562
+ if (fresh && fresh.version === target) {
2563
+ console.log(pc.green('✓') + ` Service restarted on ${pc.bold('v' + fresh.version)}`)
2564
+ } else if (fresh) {
2565
+ console.log(
2566
+ pc.yellow('⚠') +
2567
+ ` Service restarted but reports v${fresh.version} (expected v${target}).` +
2568
+ '\n' +
2569
+ pc.dim(' The unit may exec a different install — see `moi service`.')
2570
+ )
2571
+ } else {
2572
+ console.log(
2573
+ pc.yellow('⚠') +
2574
+ ' Service restarted but the server has not come back up — `moi service logs`.'
2575
+ )
2576
+ }
2577
+ } catch (err) {
2578
+ console.log(
2579
+ pc.yellow('⚠') +
2580
+ ' Could not restart the service: ' +
2581
+ (err instanceof Error ? err.message : String(err))
2582
+ )
2583
+ }
2584
+ return
2585
+ }
2586
+ console.log(
2587
+ pc.yellow('⚠') +
2588
+ ` A foreground server is still running v${info.version}` +
2589
+ (info.pid ? pc.dim(` (pid ${info.pid})`) : '') +
2590
+ '.\n' +
2591
+ pc.dim(` Restart it when convenient (Ctrl-C, then \`moi start\`) to get v${target}.`)
2592
+ )
2069
2593
  }
2070
2594
 
2071
2595
  const version = defineCommand({
2072
2596
  meta: { name: 'version', description: 'Print the moi version' },
2073
2597
  run() {
2074
- console.log(moiVersion())
2598
+ console.log(versionWithCommit())
2075
2599
  }
2076
2600
  })
2077
2601
 
2602
+ // The root help splits the surface by audience: workspace commands are the
2603
+ // agent's day-to-day toolkit (skills tell it to run them); system commands
2604
+ // manage moi itself and are for the human at the keyboard.
2605
+ const workspaceCommands = {
2606
+ bundle,
2607
+ refresh,
2608
+ builder,
2609
+ 'call-server-fn': callServerFn,
2610
+ debug,
2611
+ theme,
2612
+ config,
2613
+ env,
2614
+ scratch,
2615
+ skill,
2616
+ tab,
2617
+ tabs
2618
+ }
2619
+
2620
+ const systemCommands = {
2621
+ init,
2622
+ start,
2623
+ status,
2624
+ service,
2625
+ update,
2626
+ openclaw,
2627
+ version
2628
+ }
2629
+
2078
2630
  const main = defineCommand({
2079
2631
  // A function so the git lookup runs only for `moi --version` / `--help`, not on
2080
2632
  // every command. citty resolves a function meta (used for --version + usage).
2081
- meta: () => ({ name: 'moi', description: 'moi — local AI workspace', version: moiVersion() }),
2082
- subCommands: {
2083
- init,
2084
- start,
2085
- bundle,
2086
- builder,
2087
- refresh,
2088
- 'call-server-fn': callServerFn,
2089
- debug,
2090
- theme,
2091
- config,
2092
- env,
2093
- status,
2094
- openclaw,
2095
- scratch,
2096
- skill,
2097
- tab,
2098
- tabs,
2099
- version
2100
- }
2633
+ meta: () => ({
2634
+ name: 'moi',
2635
+ description: 'moi — local AI workspace',
2636
+ version: versionWithCommit()
2637
+ }),
2638
+ subCommands: { ...workspaceCommands, ...systemCommands }
2101
2639
  })
2102
2640
 
2103
- // Route `moi config --help` to the same terse cheat sheet as `moi config help`;
2104
- // every other command keeps citty's default usage renderer.
2641
+ type HelpCommand = { meta?: unknown }
2642
+
2643
+ async function commandDescription(cmd: HelpCommand): Promise<string> {
2644
+ const meta = typeof cmd.meta === 'function' ? await cmd.meta() : await cmd.meta
2645
+ return (meta as { description?: string })?.description ?? ''
2646
+ }
2647
+
2648
+ // Two-section root help (replaces citty's flat list). For a human, the
2649
+ // system section carries an explicit note that agents should leave those
2650
+ // commands alone; for a detected agent caller, the section is omitted
2651
+ // entirely — an agent's `moi --help` shows only the workspace toolkit.
2652
+ async function printMainHelp() {
2653
+ const pad =
2654
+ Math.max(...Object.keys({ ...workspaceCommands, ...systemCommands }).map(n => n.length)) + 4
2655
+ const row = async (name: string, cmd: HelpCommand) =>
2656
+ ' ' + pc.cyan(name.padEnd(pad)) + pc.dim(await commandDescription(cmd))
2657
+ console.log()
2658
+ console.log(
2659
+ pc.bold('moi') + pc.dim(' — local AI workspace ') + pc.dim(`v${versionWithCommit()}`)
2660
+ )
2661
+ console.log()
2662
+ console.log(pc.dim('USAGE ') + 'moi <command> [options]')
2663
+ console.log()
2664
+ console.log(pc.bold('Workspace commands:') + pc.dim(' for agents and humans alike'))
2665
+ console.log()
2666
+ for (const [name, cmd] of Object.entries(workspaceCommands)) console.log(await row(name, cmd))
2667
+ console.log()
2668
+ if (!isAgentCaller()) {
2669
+ console.log(
2670
+ pc.bold('System commands:') + pc.dim(' manage moi itself (server, service, updates)')
2671
+ )
2672
+ console.log(pc.yellow(' AGENTS: do not run these unless explicitly asked!'))
2673
+ console.log()
2674
+ for (const [name, cmd] of Object.entries(systemCommands)) console.log(await row(name, cmd))
2675
+ console.log()
2676
+ }
2677
+ console.log(pc.dim('Use moi <command> --help for more information about a command.'))
2678
+ console.log()
2679
+ }
2680
+
2681
+ // Route `moi --help` (and bare `moi`) to the two-section help, and
2682
+ // `moi config --help` to its terse cheat sheet; every other command keeps
2683
+ // citty's default usage renderer.
2105
2684
  runMain(main, {
2106
2685
  async showUsage(cmd, parent) {
2107
2686
  const meta = typeof cmd.meta === 'function' ? await cmd.meta() : await cmd.meta
2687
+ if (meta?.name === 'moi') {
2688
+ await printMainHelp()
2689
+ return
2690
+ }
2108
2691
  if (meta?.name === 'config') {
2109
2692
  printConfigHelp()
2110
2693
  return