moi-computer 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/LICENSE +95 -0
  2. package/README.md +71 -0
  3. package/bin/moi.mjs +25 -0
  4. package/bunfig.toml +3 -0
  5. package/client/CLAUDE.md +12 -0
  6. package/client/api/workspaces.ts +158 -0
  7. package/client/assets/claude.svg +3 -0
  8. package/client/assets/favicon.png +0 -0
  9. package/client/assets/hermes-nous.png +0 -0
  10. package/client/assets/mcp/.gitkeep +0 -0
  11. package/client/assets/mcp/atlassian.png +0 -0
  12. package/client/assets/mcp/discord.png +0 -0
  13. package/client/assets/mcp/figma.png +0 -0
  14. package/client/assets/mcp/github.png +0 -0
  15. package/client/assets/mcp/gitlab.png +0 -0
  16. package/client/assets/mcp/granola.png +0 -0
  17. package/client/assets/mcp/hubspot.png +0 -0
  18. package/client/assets/mcp/linear.png +0 -0
  19. package/client/assets/mcp/neon.png +0 -0
  20. package/client/assets/mcp/notion.png +0 -0
  21. package/client/assets/mcp/sentry.png +0 -0
  22. package/client/assets/mcp/slack.png +0 -0
  23. package/client/assets/mcp/stripe.png +0 -0
  24. package/client/assets/mcp/supabase.png +0 -0
  25. package/client/assets/mcp/vercel.png +0 -0
  26. package/client/assets/moi-logo.svg +11 -0
  27. package/client/assets/openclaw.svg +22 -0
  28. package/client/components/App.tsx +35 -0
  29. package/client/components/BottomPanel.tsx +33 -0
  30. package/client/components/ChatInput.tsx +62 -0
  31. package/client/components/ChatPanel.tsx +206 -0
  32. package/client/components/ChatPopup.tsx +60 -0
  33. package/client/components/CustomizePanel.tsx +117 -0
  34. package/client/components/HiddenPanel.tsx +79 -0
  35. package/client/components/HomePage.tsx +17 -0
  36. package/client/components/MarkdownContent.tsx +41 -0
  37. package/client/components/ThreadSelector.tsx +88 -0
  38. package/client/components/TurnView.tsx +618 -0
  39. package/client/components/WidgetErrorBoundary.tsx +46 -0
  40. package/client/components/WidgetFrame.tsx +66 -0
  41. package/client/components/WidgetGrid.tsx +113 -0
  42. package/client/components/WidgetShell.tsx +44 -0
  43. package/client/components/Widgets.tsx +132 -0
  44. package/client/components/WorkspacePreview.tsx +48 -0
  45. package/client/components/WorkspacesPage.tsx +237 -0
  46. package/client/components/layout/SidebarLayout.tsx +260 -0
  47. package/client/components/playground/LedLogo.tsx +181 -0
  48. package/client/components/playground/PixelPainter.tsx +105 -0
  49. package/client/components/playground/PlaygroundPage.tsx +71 -0
  50. package/client/components/routes/workspace/[id].tsx +282 -0
  51. package/client/components/ui/button.tsx +48 -0
  52. package/client/components/ui/dropdown-menu.tsx +257 -0
  53. package/client/components/ui/input.tsx +21 -0
  54. package/client/components/ui/popover.tsx +79 -0
  55. package/client/components/ui/textarea.tsx +18 -0
  56. package/client/externalize-react.ts +29 -0
  57. package/client/hooks/useChat.ts +88 -0
  58. package/client/hooks/useFitsSidebar.ts +34 -0
  59. package/client/hooks/useGridReconcile.ts +73 -0
  60. package/client/hooks/useMeiEvents.ts +66 -0
  61. package/client/hooks/useScrollFade.ts +38 -0
  62. package/client/hooks/useWidget.ts +72 -0
  63. package/client/hooks/useWidgetList.ts +30 -0
  64. package/client/hooks/useWorkspaceTheme.ts +76 -0
  65. package/client/index.css +182 -0
  66. package/client/index.html +43 -0
  67. package/client/index.tsx +19 -0
  68. package/client/lib/WorkspaceContext.tsx +24 -0
  69. package/client/lib/WorkspaceLayoutContext.tsx +92 -0
  70. package/client/lib/cn.ts +6 -0
  71. package/client/lib/grid-pack.ts +35 -0
  72. package/client/lib/group-turns.ts +44 -0
  73. package/client/lib/mcp-icons.ts +53 -0
  74. package/client/lib/ws.ts +129 -0
  75. package/client/main.tsx +23 -0
  76. package/client/store/chat.tsx +162 -0
  77. package/client/store/ui.ts +21 -0
  78. package/client/theme.css +66 -0
  79. package/lib/claude-adapter.ts +602 -0
  80. package/lib/format.ts +212 -0
  81. package/lib/themes.ts +89 -0
  82. package/lib/types.ts +144 -0
  83. package/package.json +117 -0
  84. package/server/CLAUDE.md +6 -0
  85. package/server/agent.ts +132 -0
  86. package/server/build-widget.ts +343 -0
  87. package/server/cli.ts +632 -0
  88. package/server/constants.ts +3 -0
  89. package/server/control.ts +98 -0
  90. package/server/functions-worker.ts +89 -0
  91. package/server/functions.ts +171 -0
  92. package/server/layout.ts +83 -0
  93. package/server/openclaw-adapter.ts +242 -0
  94. package/server/openclaw-gateway.ts +255 -0
  95. package/server/openclaw-session.ts +485 -0
  96. package/server/openclaw-strip.ts +134 -0
  97. package/server/openclaw.ts +206 -0
  98. package/server/registry.ts +150 -0
  99. package/server/skills-template.ts +21 -0
  100. package/server/state.ts +87 -0
  101. package/server/theme.ts +55 -0
  102. package/server/web.ts +321 -0
  103. package/server/widgets.ts +254 -0
  104. package/tsconfig.json +21 -0
  105. package/workspace/.claude/skills/widgets/DESIGN.md +630 -0
  106. package/workspace/.claude/skills/widgets/SKILL.md +176 -0
package/server/cli.ts ADDED
@@ -0,0 +1,632 @@
1
+ #!/usr/bin/env bun
2
+ import { defineCommand, runMain } from 'citty'
3
+ import Table from 'cli-table3'
4
+ import { mkdir } from 'node:fs/promises'
5
+ import { join, resolve } from 'path'
6
+ import pc from 'picocolors'
7
+
8
+ import { COLOR_THEMES, FONT_THEMES } from '@/lib/themes'
9
+ import type { ColorTheme, FontTheme } from '@/lib/themes'
10
+
11
+ import { CONTROL_PORT, PORT } from './constants'
12
+ import { type OpenClawAgent, discoverOpenClawAgents } from './openclaw'
13
+ import { registerWorkspace } from './registry'
14
+ import { installBundledSkills } from './skills-template'
15
+
16
+ // ---- helpers ----------------------------------------------------------------
17
+
18
+ async function isServerRunning(): Promise<boolean> {
19
+ return new Promise(resolve => {
20
+ const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
21
+ const timer = setTimeout(() => {
22
+ ws.close()
23
+ resolve(false)
24
+ }, 600)
25
+ ws.onopen = () => {
26
+ clearTimeout(timer)
27
+ ws.close()
28
+ resolve(true)
29
+ }
30
+ ws.onerror = () => {
31
+ clearTimeout(timer)
32
+ resolve(false)
33
+ }
34
+ })
35
+ }
36
+
37
+ async function waitForServer(timeoutMs = 10_000): Promise<boolean> {
38
+ const deadline = Date.now() + timeoutMs
39
+ while (Date.now() < deadline) {
40
+ if (await isServerRunning()) return true
41
+ await Bun.sleep(200)
42
+ }
43
+ return false
44
+ }
45
+
46
+ async function registerViaControl(absPath: string): Promise<string> {
47
+ return new Promise((res, rej) => {
48
+ const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
49
+ ws.onopen = () => ws.send(JSON.stringify({ type: 'workspace:register', path: absPath }))
50
+ ws.onmessage = event => {
51
+ const data = JSON.parse(String(event.data))
52
+ if (data.id) {
53
+ ws.close()
54
+ res(data.id)
55
+ }
56
+ }
57
+ ws.onerror = () => rej(new Error('Could not connect to control server'))
58
+ })
59
+ }
60
+
61
+ async function openBrowser(url: string) {
62
+ try {
63
+ if (process.platform === 'darwin') await Bun.$`open ${url}`.quiet()
64
+ else if (process.platform === 'linux') await Bun.$`xdg-open ${url}`.quiet()
65
+ } catch {}
66
+ }
67
+
68
+ // Spawn the server as a child with cwd=projectRoot so bunfig.toml is found at Bun startup.
69
+ // bunfig.toml is read before any JS runs, so process.chdir() is too late.
70
+ // MOI_SERVER=1 tells the child it is the actual server process. No `--hot`:
71
+ // frontend HMR comes from Bun.serve's dev bundler, and server reloads are a
72
+ // full process restart driven by the dev supervisor (see runDevSupervisor).
73
+ function spawnServer(
74
+ projectRoot: string,
75
+ env: Record<string, string | undefined> = process.env
76
+ ): ReturnType<typeof Bun.spawn> {
77
+ return Bun.spawn(['bun', import.meta.filename, 'start'], {
78
+ stdin: 'inherit',
79
+ stdout: 'inherit',
80
+ stderr: 'inherit',
81
+ cwd: projectRoot,
82
+ env: { ...env, MOI_SERVER: '1' }
83
+ })
84
+ }
85
+
86
+ // Dev supervisor: run the server as a child WITHOUT `bun --hot`, watch the
87
+ // server-side source (`server/`, `lib/`) and full-restart the child on change.
88
+ // Client files are intentionally not watched here — Bun.serve owns frontend HMR
89
+ // and patches the browser in place. The child shuts down gracefully on SIGTERM
90
+ // (closing servers + killing function workers), so restarts leak nothing.
91
+ async function runDevSupervisor(
92
+ projectRoot: string,
93
+ env: Record<string, string | undefined>
94
+ ): Promise<void> {
95
+ const { watch } = await import('node:fs')
96
+
97
+ let child = spawnServer(projectRoot, env)
98
+ let restarting = false
99
+ let debounce: ReturnType<typeof setTimeout> | undefined
100
+
101
+ async function restart(reason: string) {
102
+ if (restarting) return
103
+ restarting = true
104
+ console.log(pc.dim(`\n↻ ${reason} — restarting server…`))
105
+ try {
106
+ child.kill('SIGTERM')
107
+ } catch {}
108
+ const sigkill = setTimeout(() => {
109
+ try {
110
+ child.kill('SIGKILL')
111
+ } catch {}
112
+ }, 3000)
113
+ await child.exited
114
+ clearTimeout(sigkill)
115
+ restarting = false
116
+ child = spawnServer(projectRoot, env)
117
+ }
118
+
119
+ for (const dir of ['server', 'lib']) {
120
+ watch(join(projectRoot, dir), { recursive: true }, (_event, file) => {
121
+ if (!file || !file.endsWith('.ts')) return
122
+ clearTimeout(debounce)
123
+ debounce = setTimeout(() => restart(`${file} changed`), 100)
124
+ })
125
+ }
126
+
127
+ // Forward termination to the child, then exit the supervisor.
128
+ for (const sig of ['SIGINT', 'SIGTERM'] as const) {
129
+ process.on(sig, () => {
130
+ try {
131
+ child.kill('SIGTERM')
132
+ } catch {}
133
+ process.exit(0)
134
+ })
135
+ }
136
+
137
+ // Keep the supervisor alive indefinitely.
138
+ await new Promise<void>(() => {})
139
+ }
140
+
141
+ // ---- commands ---------------------------------------------------------------
142
+
143
+ const init = defineCommand({
144
+ meta: {
145
+ name: 'init',
146
+ description: 'Initialize workspace, copy skills and scaffold folder with widgets'
147
+ },
148
+ args: {
149
+ dir: {
150
+ type: 'positional',
151
+ default: '.',
152
+ description: 'Target directory (default: current)'
153
+ },
154
+ web: {
155
+ type: 'boolean',
156
+ default: false,
157
+ description: 'Start the web server if not already running'
158
+ }
159
+ },
160
+ async run({ args }) {
161
+ const target = resolve(args.dir)
162
+ const projectRoot = join(import.meta.dir, '..')
163
+ const isInteractive = process.stdout.isTTY
164
+
165
+ await mkdir(target, { recursive: true })
166
+ await installBundledSkills(join(target, '.claude', 'skills'))
167
+
168
+ // Always register the workspace in the persistent registry
169
+ const entry = await registerWorkspace(target)
170
+
171
+ console.log('\n' + pc.green('✓') + ' Initialized ' + pc.bold(target))
172
+ console.log(' Skills installed — ask Claude to build a widget to get started\n')
173
+
174
+ // If --web and server not running, start it (stay alive as wrapper)
175
+ let running = await isServerRunning()
176
+
177
+ if (!running && args.web) {
178
+ console.log(pc.dim(' Starting server…'))
179
+ const proc = spawnServer(projectRoot)
180
+ running = await waitForServer()
181
+ if (!running) {
182
+ console.error(pc.red(' Server failed to start\n'))
183
+ await proc.exited
184
+ process.exit(1)
185
+ }
186
+ const url = `http://localhost:${PORT}/workspace/${entry.id}`
187
+ console.log(pc.green('✓') + ' Server started on http://localhost:' + PORT)
188
+ if (isInteractive) console.log(' Opening ' + pc.bold(url))
189
+ console.log(pc.dim(' Press Ctrl+C to stop\n'))
190
+ if (isInteractive) await openBrowser(url)
191
+ await proc.exited
192
+ process.exit(proc.exitCode ?? 0)
193
+ }
194
+
195
+ if (running) {
196
+ // Server already running — notify it and open (browser only in interactive mode)
197
+ await registerViaControl(target)
198
+ const url = `http://localhost:${PORT}/workspace/${entry.id}`
199
+ if (isInteractive) {
200
+ console.log(' Opening ' + pc.bold(url) + '\n')
201
+ await openBrowser(url)
202
+ } else {
203
+ console.log(' Ready at ' + pc.bold(url) + '\n')
204
+ }
205
+ process.exit(0)
206
+ }
207
+
208
+ // Server not running and --web not passed
209
+ console.log(' Run ' + pc.bold('moi start') + ' to open in the browser\n')
210
+ }
211
+ })
212
+
213
+ const start = defineCommand({
214
+ meta: { name: 'start', description: 'Start the moi web server' },
215
+ args: {
216
+ port: {
217
+ type: 'string',
218
+ description: 'HTTP port to listen on (default: 3000)'
219
+ }
220
+ },
221
+ async run({ args }) {
222
+ const projectRoot = join(import.meta.dir, '..')
223
+ // Undocumented: --dev runs the watch-and-full-restart dev supervisor.
224
+ const dev = process.argv.includes('--dev')
225
+
226
+ // Launcher path: we are the CLI, not the server. Decide whether to bail
227
+ // (a server is already up), run the dev supervisor, or spawn a one-shot
228
+ // server. Skipped when MOI_SERVER=1 (we are the spawned server itself).
229
+ if (!process.env.MOI_SERVER) {
230
+ if (await isServerRunning()) {
231
+ console.log(
232
+ '\n' + pc.yellow('◆') + ' Server is already running on http://localhost:' + PORT + '\n'
233
+ )
234
+ process.exit(0)
235
+ }
236
+
237
+ // Spawn server with correct cwd so bunfig.toml is picked up at Bun startup.
238
+ const env = args.port ? { ...process.env, PORT: args.port } : process.env
239
+ if (dev) {
240
+ await runDevSupervisor(projectRoot, env)
241
+ return
242
+ }
243
+ const proc = spawnServer(projectRoot, env)
244
+ await proc.exited
245
+ process.exit(proc.exitCode ?? 0)
246
+ }
247
+
248
+ // This IS the server process (MOI_SERVER=1, cwd=projectRoot, bunfig.toml loaded).
249
+ await import('./web')
250
+ console.log(`\n${pc.green('✓')} Server started on http://localhost:${PORT}`)
251
+ console.log(pc.dim(' Press Ctrl+C to stop\n'))
252
+ // Stay alive as the server
253
+ }
254
+ })
255
+
256
+ function colorStatus(status: string) {
257
+ if (status === 'built') return pc.green(status)
258
+ if (status === 'failed') return pc.red(status)
259
+ return pc.dim(status)
260
+ }
261
+
262
+ const bundle = defineCommand({
263
+ meta: { name: 'bundle', description: 'Rebuild changed widgets' },
264
+ args: {
265
+ dir: {
266
+ type: 'positional',
267
+ default: '.',
268
+ description: 'Workspace directory (default: current)'
269
+ },
270
+ force: {
271
+ type: 'boolean',
272
+ description: 'Rebuild all widgets, ignoring file modification times',
273
+ default: false
274
+ }
275
+ },
276
+ run({ args }) {
277
+ const path = resolve(args.dir)
278
+ const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
279
+
280
+ ws.onopen = () => ws.send(JSON.stringify({ type: 'bundle', path, force: args.force }))
281
+
282
+ ws.onmessage = event => {
283
+ const results = JSON.parse(String(event.data))
284
+ if (!Array.isArray(results)) return
285
+
286
+ const table = new Table({ head: [pc.bold('widget'), pc.bold('status')] })
287
+ for (const r of results as { name: string; status: string; error?: string }[]) {
288
+ table.push([r.name, colorStatus(r.status)])
289
+ }
290
+ console.log('\n' + table.toString())
291
+
292
+ const failed = results.filter(
293
+ (r: { status: string; error?: string }) => r.status === 'failed'
294
+ )
295
+ if (failed.length) {
296
+ console.log()
297
+ for (const f of failed) {
298
+ console.log(pc.red(pc.bold(f.name + ':')))
299
+ console.log(' ' + f.error + '\n')
300
+ }
301
+ }
302
+
303
+ ws.close()
304
+ process.exit(failed.length > 0 ? 1 : 0)
305
+ }
306
+
307
+ ws.onerror = () => {
308
+ console.error('Could not connect to control server. Is the main process running?')
309
+ process.exit(1)
310
+ }
311
+ }
312
+ })
313
+
314
+ const refresh = defineCommand({
315
+ meta: {
316
+ name: 'refresh',
317
+ description:
318
+ 'Refresh widget data without rebuilding. Use after the agent mutates underlying data.'
319
+ },
320
+ run() {
321
+ const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
322
+
323
+ ws.onopen = () => ws.send(JSON.stringify({ type: 'widget:refresh' }))
324
+
325
+ ws.onmessage = event => {
326
+ const data = JSON.parse(String(event.data))
327
+ if (data.error) {
328
+ console.error('\n' + pc.red('✗') + ' ' + data.error + '\n')
329
+ ws.close()
330
+ process.exit(1)
331
+ }
332
+ console.log('\n' + pc.green('✓') + ' Refresh signal sent\n')
333
+ ws.close()
334
+ process.exit(0)
335
+ }
336
+
337
+ ws.onerror = () => {
338
+ console.error('Could not connect to control server. Is the main process running?')
339
+ process.exit(1)
340
+ }
341
+ }
342
+ })
343
+
344
+ function hexToRgb(h: string): [number, number, number] {
345
+ const n = parseInt(h.replace('#', ''), 16)
346
+ return [(n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]
347
+ }
348
+
349
+ // Truecolor swatch using raw ANSI 24-bit escapes (picocolors maxes at 8 colors).
350
+ // Falls back to blank spaces when stdout is not a TTY, keeping piped output clean.
351
+ function swatch(bg?: string, fg?: string): string {
352
+ if (!process.stdout.isTTY || !bg) return ' '
353
+ const [br, bgg, bb] = hexToRgb(bg)
354
+ const [fr, fgg, fb] = hexToRgb(fg ?? '#000000')
355
+ return `\x1b[48;2;${br};${bgg};${bb}m\x1b[38;2;${fr};${fgg};${fb}m Aa \x1b[0m`
356
+ }
357
+
358
+ const theme = defineCommand({
359
+ meta: { name: 'theme', description: 'Show or set the workspace font and color themes' },
360
+ args: {
361
+ dir: {
362
+ type: 'positional',
363
+ default: '.',
364
+ description: 'Workspace directory (default: current)'
365
+ },
366
+ font: { type: 'string', description: 'Font theme key to apply' },
367
+ color: { type: 'string', description: 'Color preset key to apply' }
368
+ },
369
+ run({ args }) {
370
+ const path = resolve(args.dir)
371
+ const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
372
+
373
+ ws.onopen = () =>
374
+ ws.send(
375
+ JSON.stringify({
376
+ type: 'theme',
377
+ path,
378
+ font: args.font ?? null,
379
+ color: args.color ?? null
380
+ })
381
+ )
382
+
383
+ ws.onmessage = event => {
384
+ const res = JSON.parse(String(event.data))
385
+
386
+ if (res.error) {
387
+ console.error('\n' + pc.red(pc.bold('Error:')) + ' ' + res.error + '\n')
388
+ ws.close()
389
+ process.exit(1)
390
+ }
391
+
392
+ if (res.ok) {
393
+ console.log()
394
+ if (res.font) {
395
+ const config = FONT_THEMES[res.font as FontTheme]
396
+ console.log(
397
+ pc.green('✓') +
398
+ ' Font set to ' +
399
+ pc.bold(config.label) +
400
+ pc.dim(` (${config.sans} / ${config.mono})`)
401
+ )
402
+ }
403
+ if (res.color) {
404
+ const preset = COLOR_THEMES[res.color as ColorTheme]
405
+ const chip = swatch(preset.background, preset.foreground)
406
+ console.log(pc.green('✓') + ' Color set to ' + pc.bold(preset.label) + ' ' + chip)
407
+ }
408
+ console.log()
409
+ ws.close()
410
+ process.exit(0)
411
+ }
412
+
413
+ const currentFont: FontTheme = res.currentFont ?? 'default'
414
+ const currentColor: ColorTheme | null = res.currentColor ?? null
415
+ console.log('\n' + pc.bold('moi theme') + ' — workspace appearance')
416
+ console.log(pc.dim(' Usage: moi theme --font=<key> --color=<key>') + '\n')
417
+
418
+ const fontTable = new Table({
419
+ head: ['', 'key', 'label', 'sans', 'mono', 'feel'].map(h => pc.bold(h)),
420
+ style: { border: [], head: [] }
421
+ })
422
+ for (const key of Object.keys(FONT_THEMES) as FontTheme[]) {
423
+ const f = FONT_THEMES[key]
424
+ const selected = key === currentFont
425
+ fontTable.push([
426
+ selected ? pc.green('→') : '',
427
+ selected ? pc.bold(key) : key,
428
+ f.label,
429
+ pc.dim(f.sans),
430
+ pc.dim(f.mono),
431
+ pc.dim(f.feel)
432
+ ])
433
+ }
434
+ console.log(pc.dim(' Fonts'))
435
+ console.log(fontTable.toString() + '\n')
436
+
437
+ const colorTable = new Table({
438
+ head: ['', 'key', 'label', 'swatch', 'feel'].map(h => pc.bold(h)),
439
+ style: { border: [], head: [] }
440
+ })
441
+ for (const key of Object.keys(COLOR_THEMES) as ColorTheme[]) {
442
+ const c = COLOR_THEMES[key]
443
+ const selected = key === currentColor
444
+ colorTable.push([
445
+ selected ? pc.green('→') : '',
446
+ selected ? pc.bold(key) : key,
447
+ c.label,
448
+ swatch(c.background, c.foreground),
449
+ pc.dim(c.feel)
450
+ ])
451
+ }
452
+ console.log(pc.dim(' Colors'))
453
+ console.log(colorTable.toString() + '\n')
454
+
455
+ ws.close()
456
+ process.exit(0)
457
+ }
458
+
459
+ ws.onerror = () => {
460
+ console.error('Could not connect to control server. Is the main process running?')
461
+ process.exit(1)
462
+ }
463
+ }
464
+ })
465
+
466
+ const status = defineCommand({
467
+ meta: { name: 'status', description: 'Show server status and registered workspaces' },
468
+ async run() {
469
+ const running = await isServerRunning()
470
+
471
+ if (!running) {
472
+ console.log('\n' + pc.dim('○') + ' Server is ' + pc.bold('not running') + '\n')
473
+ process.exit(0)
474
+ }
475
+
476
+ console.log(
477
+ '\n' +
478
+ pc.green('●') +
479
+ ' Server is ' +
480
+ pc.bold('running') +
481
+ pc.dim(` (http port: ${PORT}, control port: ${CONTROL_PORT})`)
482
+ )
483
+
484
+ await new Promise<void>((resolve, reject) => {
485
+ const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
486
+
487
+ ws.onopen = () => ws.send(JSON.stringify({ type: 'workspace:list' }))
488
+
489
+ ws.onmessage = event => {
490
+ const res = JSON.parse(String(event.data))
491
+ const workspaces: { id: string; path: string; addedAt: string }[] = res.workspaces ?? []
492
+ const n = workspaces.length
493
+ console.log(pc.dim(` ${n} workspace${n === 1 ? '' : 's'} registered\n`))
494
+
495
+ ws.close()
496
+ resolve()
497
+ }
498
+
499
+ ws.onerror = () => reject(new Error('Could not connect to control server'))
500
+ })
501
+
502
+ process.exit(0)
503
+ }
504
+ })
505
+
506
+ // ---- openclaw subcommands ---------------------------------------------------
507
+
508
+ // Match an `agent` argument against `agentId` (exact) or `name`
509
+ // (case-insensitive). Returns the matching agent or null.
510
+ function findAgent(agents: OpenClawAgent[], query: string): OpenClawAgent | null {
511
+ const exact = agents.find(a => a.agentId === query)
512
+ if (exact) return exact
513
+ const q = query.toLowerCase()
514
+ return agents.find(a => a.name?.toLowerCase() === q) ?? null
515
+ }
516
+
517
+ function printAgentTable(agents: OpenClawAgent[]) {
518
+ const table = new Table({
519
+ head: ['', pc.bold('agentId'), pc.bold('name'), pc.bold('workspace')],
520
+ style: { border: [], head: [] }
521
+ })
522
+ for (const a of agents) {
523
+ table.push([
524
+ a.isDefault ? pc.green('●') : '',
525
+ a.isDefault ? pc.bold(a.agentId) : a.agentId,
526
+ a.name ?? pc.dim('—'),
527
+ pc.dim(a.path)
528
+ ])
529
+ }
530
+ console.log(table.toString())
531
+ }
532
+
533
+ const openclawInit = defineCommand({
534
+ meta: {
535
+ name: 'init',
536
+ description:
537
+ 'Install moi skills into an OpenClaw agent workspace. Run without args to list discovered agents.'
538
+ },
539
+ args: {
540
+ agent: {
541
+ type: 'positional',
542
+ required: false,
543
+ description: 'Agent id or name (omit to list agents)'
544
+ }
545
+ },
546
+ async run({ args }) {
547
+ const agents = await discoverOpenClawAgents()
548
+ if (agents.length === 0) {
549
+ console.error(
550
+ '\n' +
551
+ pc.red('✗') +
552
+ ' No OpenClaw agents discovered.\n' +
553
+ pc.dim(
554
+ ' Make sure the OpenClaw gateway is running and ~/.openclaw/openclaw.json is set.\n'
555
+ )
556
+ )
557
+ process.exit(1)
558
+ }
559
+
560
+ if (!args.agent) {
561
+ console.log('\n' + pc.bold('OpenClaw agents'))
562
+ console.log(
563
+ pc.dim(' Run ' + pc.bold('moi openclaw init <agentId>') + ' to install skills.\n')
564
+ )
565
+ printAgentTable(agents)
566
+ console.log()
567
+ process.exit(0)
568
+ }
569
+
570
+ const target = findAgent(agents, args.agent)
571
+ if (!target) {
572
+ console.error('\n' + pc.red('✗') + ' Agent not found: ' + pc.bold(args.agent) + '\n')
573
+ console.log(' Available:\n')
574
+ printAgentTable(agents)
575
+ console.log()
576
+ process.exit(1)
577
+ }
578
+
579
+ // Copy each shipped skill folder into <agent-workspace>/skills/<name>/.
580
+ // OpenClaw resolves <workspace>/skills with the highest precedence, so
581
+ // these win over any same-named bundled or per-user skill.
582
+ const skillsRoot = join(target.path, 'skills')
583
+ await installBundledSkills(skillsRoot)
584
+
585
+ // Register in the moi registry so the agent's workspace appears in the
586
+ // UI workspace list. Mirrors what `moi init` does for Claude Code.
587
+ const entry = await registerWorkspace(target.path, {
588
+ type: 'openclaw',
589
+ name: target.name,
590
+ agentId: target.agentId,
591
+ isDefault: target.isDefault,
592
+ lastRunAt: target.lastRunAt
593
+ })
594
+
595
+ console.log('\n' + pc.green('✓') + ' Installed skills to ' + pc.bold(skillsRoot))
596
+ console.log(
597
+ pc.dim(' Agent: ') +
598
+ pc.bold(target.agentId) +
599
+ (target.name ? pc.dim(' (' + target.name + ')') : '')
600
+ )
601
+ const isInteractive = process.stdout.isTTY
602
+ const running = await isServerRunning()
603
+ if (running) {
604
+ const url = `http://localhost:${PORT}/workspace/${entry.id}`
605
+ // Notify the running server so it picks up the new entry without a
606
+ // restart, then open (browser only in interactive mode) — same shape
607
+ // as `moi init`'s already-running branch.
608
+ await registerViaControl(target.path)
609
+ if (isInteractive) {
610
+ console.log(' Opening ' + pc.bold(url) + '\n')
611
+ await openBrowser(url)
612
+ } else {
613
+ console.log(' Ready at ' + pc.bold(url) + '\n')
614
+ }
615
+ } else {
616
+ console.log(' Run ' + pc.bold('moi start') + ' to open in the browser\n')
617
+ }
618
+ process.exit(0)
619
+ }
620
+ })
621
+
622
+ const openclaw = defineCommand({
623
+ meta: { name: 'openclaw', description: 'OpenClaw integration commands' },
624
+ subCommands: { init: openclawInit }
625
+ })
626
+
627
+ const main = defineCommand({
628
+ meta: { name: 'moi', description: 'moi — local AI workspace' },
629
+ subCommands: { init, start, bundle, refresh, theme, status, openclaw }
630
+ })
631
+
632
+ runMain(main)
@@ -0,0 +1,3 @@
1
+ export const PORT = Number(process.env.PORT) || 3000
2
+ // M=13, E=5, I=9 -> 13059
3
+ export const CONTROL_PORT = 13059