moi-computer 0.12.0 → 0.12.1-next.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 (367) hide show
  1. package/README.md +27 -27
  2. package/bin/moi.mjs +2 -2
  3. package/client/AGENTS.md +7 -4
  4. package/client/api/app-config.ts +3 -2
  5. package/client/api/app-ui-keys.ts +1 -1
  6. package/client/api/workspace-keys.ts +2 -4
  7. package/client/app/{AppRouter.tsx → app-router.tsx} +4 -4
  8. package/client/app/routes/{HomeRoute.tsx → home-route.tsx} +2 -2
  9. package/client/app/routes/{WorkspaceRoute.tsx → workspace-route.tsx} +20 -31
  10. package/client/app/shell/{SidebarLayout.tsx → sidebar-layout.tsx} +10 -10
  11. package/client/dev/index.html +43 -0
  12. package/client/dev/index.ts +15 -0
  13. package/client/features/applets/{AppletContainer.tsx → applet-container.tsx} +1 -1
  14. package/client/features/applets/applet-runtime.ts +11 -13
  15. package/client/features/applets/applet-thumbnail.ts +1 -1
  16. package/client/features/applets/{useApplet.ts → use-applet.ts} +2 -2
  17. package/client/features/applets/{WidgetShell.tsx → widget-shell.tsx} +4 -4
  18. package/client/features/chat/applet-chat-intents.ts +33 -14
  19. package/client/features/chat/{ChatPanel.tsx → chat-panel.tsx} +80 -59
  20. package/client/features/chat/chat-popup.tsx +171 -0
  21. package/client/features/chat/chat-send.ts +33 -1
  22. package/client/features/chat/chat-store.ts +10 -0
  23. package/client/features/chat/composer/attachments/{DrawingAttachmentChip.tsx → drawing-attachment-chip.tsx} +1 -1
  24. package/client/features/chat/composer/attachments/{FileAttachmentChip.tsx → file-attachment-chip.tsx} +1 -1
  25. package/client/features/chat/composer/attachments/{TextAttachmentChip.tsx → text-attachment-chip.tsx} +1 -1
  26. package/client/features/chat/composer/banners/{ComposerBanner.tsx → composer-banner.tsx} +0 -14
  27. package/client/features/chat/composer/banners/{ErrorBanner.tsx → error-banner.tsx} +1 -1
  28. package/client/features/chat/composer/banners/{SkillUpdateBanner.tsx → skill-update-banner.tsx} +3 -3
  29. package/client/features/chat/composer/{ChatComposer.tsx → chat-composer.tsx} +31 -33
  30. package/client/features/chat/composer/{ModelPicker.tsx → model-picker.tsx} +4 -4
  31. package/client/features/chat/composer/{useWorkspaceComposerState.tsx → use-workspace-composer-state.tsx} +14 -30
  32. package/client/features/chat/composer/{useWorkspaceSkillUpdates.ts → use-workspace-skill-updates.ts} +1 -1
  33. package/client/features/chat/connection/chat-frames.ts +15 -8
  34. package/client/features/chat/messages/{ChatEmptyState.tsx → chat-empty-state.tsx} +37 -23
  35. package/client/features/chat/messages/fork-history.ts +14 -0
  36. package/client/features/chat/messages/{MarkdownContent.tsx → markdown-content.tsx} +4 -4
  37. package/client/features/chat/messages/tool-group/index.ts +1 -1
  38. package/client/features/chat/messages/tool-group/{ReadImagePreview.tsx → read-image-preview.tsx} +2 -2
  39. package/client/features/chat/messages/tool-group/{SubagentCard.tsx → subagent-card.tsx} +3 -3
  40. package/client/features/chat/messages/tool-group/{TimelineRow.tsx → timeline-row.tsx} +1 -1
  41. package/client/features/chat/messages/tool-group/{ToolCallGroup.tsx → tool-call-group.tsx} +8 -8
  42. package/client/features/chat/messages/tool-group/{ToolOutput.tsx → tool-output.tsx} +1 -1
  43. package/client/features/chat/messages/{TurnView.tsx → turn-view.tsx} +4 -4
  44. package/client/features/chat/sessions/api.ts +109 -19
  45. package/client/features/chat/sessions/browser-tab-state.ts +30 -7
  46. package/client/features/chat/sessions/{ChatSelector.tsx → chat-selector.tsx} +139 -80
  47. package/client/features/chat/sessions/use-selected-session.ts +351 -0
  48. package/client/features/chat/{useChat.ts → use-chat.ts} +46 -48
  49. package/client/features/collab/client.ts +10 -11
  50. package/client/features/collab/hooks.tsx +6 -11
  51. package/client/features/collab/host-state.ts +57 -128
  52. package/client/features/collab/provider.tsx +3 -3
  53. package/client/features/collab/proxy-user.ts +1 -1
  54. package/client/features/collab/testing/fake-engine.ts +6 -27
  55. package/client/features/collab/workspace-users-menu.tsx +3 -7
  56. package/client/features/connectors/mcp-icons.ts +1 -1
  57. package/client/features/connectors/{McpServerCards.tsx → mcp-server-cards.tsx} +1 -1
  58. package/client/features/{home/workspace-setup/DemoDialog.tsx → demo/demo-dialog.tsx} +6 -6
  59. package/client/features/dev/chat-states-fixtures.ts +4 -4
  60. package/client/features/dev/{ChatStatesPage.tsx → chat-states-page.tsx} +6 -6
  61. package/client/features/dev/collab/local-user-settings.tsx +4 -4
  62. package/client/features/dev/{DevIndexPage.tsx → dev-index-page.tsx} +7 -1
  63. package/client/features/dev/{DevRoutes.tsx → dev-routes.tsx} +8 -6
  64. package/client/features/dev/workspace-setup-mocks.ts +102 -0
  65. package/client/features/dev/workspace-setup-page.tsx +11 -0
  66. package/client/features/dev/workspace-setup-preview.tsx +226 -0
  67. package/client/features/drawings/{DrawingToolbar.tsx → drawing-toolbar.tsx} +1 -1
  68. package/client/features/drawings/{useChatAnnotation.ts → use-chat-annotation.ts} +29 -23
  69. package/client/features/drawings/{useDrawingLayer.ts → use-drawing-layer.ts} +1 -1
  70. package/client/features/drawings/{useViewBuilderSketch.ts → use-view-sketch.ts} +8 -8
  71. package/client/features/harness/api.ts +36 -0
  72. package/client/features/harness/device-login-steps.tsx +97 -0
  73. package/client/features/home/api.ts +1 -81
  74. package/client/features/home/{HomeLogo.tsx → home-logo.tsx} +1 -1
  75. package/client/features/home/{HomePage.tsx → home-page.tsx} +16 -20
  76. package/client/features/overview/api.ts +2 -2
  77. package/client/features/overview/default/registry.tsx +3 -5
  78. package/client/features/overview/default/{ViewsWidget.tsx → views-widget.tsx} +6 -13
  79. package/client/features/overview/{HiddenPanel.tsx → hidden-panel.tsx} +2 -2
  80. package/client/features/overview/{Overview.tsx → overview.tsx} +9 -12
  81. package/client/features/overview/{WidgetCanvas.tsx → widget-canvas.tsx} +1 -1
  82. package/client/features/overview/{WidgetFrame.tsx → widget-frame.tsx} +1 -1
  83. package/client/features/overview/workspace-name.tsx +55 -0
  84. package/client/features/scratchpad/{Scratchpad.tsx → scratchpad.tsx} +7 -7
  85. package/client/features/scratchpad/{useScratchpadSnapshot.tsx → use-scratchpad-snapshot.tsx} +3 -3
  86. package/client/features/settings/api.ts +1 -1
  87. package/client/features/settings/{ConnectorsSettings.tsx → connectors-settings.tsx} +3 -3
  88. package/client/features/settings/{EnvironmentSettings.tsx → environment-settings.tsx} +3 -3
  89. package/client/features/settings/{GeneralSettings.tsx → general-settings.tsx} +5 -5
  90. package/client/features/settings/{useEnvVars.ts → use-env-vars.ts} +1 -1
  91. package/client/features/settings/{WorkspaceIconPicker.tsx → workspace-icon-picker.tsx} +1 -1
  92. package/client/features/settings/{WorkspaceSettingsDialog.tsx → workspace-settings-dialog.tsx} +3 -3
  93. package/client/features/update/api.ts +1 -1
  94. package/client/features/views/api.ts +64 -131
  95. package/client/features/views/pending-view-screen.tsx +282 -0
  96. package/client/features/views/use-view-actions.ts +151 -0
  97. package/client/features/views/use-view-drafts.ts +88 -0
  98. package/client/features/views/{ViewManager.tsx → view-manager.tsx} +13 -13
  99. package/client/features/views/view-presentation.ts +4 -5
  100. package/client/features/views/view-submission.ts +88 -0
  101. package/client/features/workspace/add/api.ts +80 -0
  102. package/client/features/{home/workspace-setup/CreateWorkspaceDialog.tsx → workspace/add/create-workspace-dialog.tsx} +56 -42
  103. package/client/features/workspace/add/import-workspace-dialog.tsx +81 -0
  104. package/client/features/{home/workspace-setup/useWorkspaceImport.ts → workspace/add/use-workspace-import.ts} +1 -1
  105. package/client/features/workspace/add/workspace-agent-options.ts +53 -0
  106. package/client/features/{home/workspace-setup/WorkspaceAgentStep.tsx → workspace/add/workspace-agent-selector.tsx} +59 -98
  107. package/client/features/{home/workspace-setup/WorkspaceDialogContent.tsx → workspace/add/workspace-dialog-content.tsx} +1 -1
  108. package/client/features/workspace/api.ts +24 -15
  109. package/client/features/workspace/browser-tab-state.ts +16 -9
  110. package/client/features/workspace/moi-context.ts +14 -16
  111. package/client/features/workspace/setup/workspace-login-state.tsx +175 -0
  112. package/client/features/workspace/setup/workspace-recovery-states.tsx +125 -0
  113. package/client/features/workspace/setup/workspace-setup-panel.tsx +18 -0
  114. package/client/features/workspace/setup/workspace-setup.tsx +77 -0
  115. package/client/features/workspace/setup/workspace-welcome-state.tsx +81 -0
  116. package/client/features/workspace/tab-resolution.ts +16 -29
  117. package/client/features/workspace/{ThemePanel.tsx → theme-panel.tsx} +3 -3
  118. package/client/features/workspace/use-workspace-navigation.ts +245 -0
  119. package/client/features/workspace/workspace-content.tsx +641 -0
  120. package/client/features/workspace/workspace-identity.tsx +40 -0
  121. package/client/features/workspace/workspace-menu.tsx +63 -0
  122. package/client/features/{home → workspace}/workspace-presentation.tsx +10 -3
  123. package/client/features/workspace/workspace-screen.tsx +28 -0
  124. package/client/features/workspace/{WorkspaceSplitLayout.tsx → workspace-split-layout.tsx} +1 -1
  125. package/client/features/workspace/{WorkspaceTabs.tsx → workspace-tabs.tsx} +2 -2
  126. package/client/index.css +2 -2
  127. package/client/index.html +1 -1
  128. package/client/index.tsx +5 -1
  129. package/client/lib/agent-availability.ts +0 -5
  130. package/client/main.tsx +1 -1
  131. package/client/runtime/{useWorkspaceEvents.ts → use-workspace-events.ts} +10 -18
  132. package/client/store/ui.ts +25 -29
  133. package/dist/chunk-08ndj2rg.js +2 -0
  134. package/dist/chunk-2x040tmg.js +68 -0
  135. package/dist/chunk-3smxq0ts.js +1 -0
  136. package/dist/chunk-68ch5hs8.js +2 -0
  137. package/dist/{chunk-z3byfve5.js → chunk-9vg3xa81.js} +2 -2
  138. package/dist/chunk-c2p00p9j.css +1 -0
  139. package/dist/chunk-cs833y9j.js +1 -0
  140. package/dist/{chunk-97eg9mjn.js → chunk-d7cbm65e.js} +1 -1
  141. package/dist/{chunk-efdyz6xp.js → chunk-hvh9f5h0.js} +1 -1
  142. package/dist/{chunk-vfpsc75k.js → chunk-jvyvwwv3.js} +1 -1
  143. package/dist/chunk-nwevqe86.js +10 -0
  144. package/dist/{chunk-3a48fyf7.js → chunk-q0gbdts4.js} +4 -4
  145. package/dist/chunk-rt30jbcm.js +1 -0
  146. package/dist/chunk-y5y3kj67.js +1 -0
  147. package/dist/index.html +2 -2
  148. package/lib/format.ts +1 -1
  149. package/lib/harness-instructions.ts +30 -0
  150. package/lib/ids.ts +3 -6
  151. package/lib/moi-context.ts +102 -75
  152. package/lib/navigation.ts +48 -87
  153. package/lib/scratchpad-skew.ts +3 -3
  154. package/lib/session-drafts.ts +10 -0
  155. package/lib/types.ts +92 -51
  156. package/lib/update.ts +1 -1
  157. package/lib/view-build-directives.ts +12 -0
  158. package/lib/workspace-layout.ts +1 -1
  159. package/lib/workspace-tabs.ts +12 -7
  160. package/package.json +7 -2
  161. package/server/AGENTS.md +10 -4
  162. package/server/README.md +102 -0
  163. package/server/agent-launcher.ts +27 -0
  164. package/server/api/harnesses.ts +56 -0
  165. package/server/{api.ts → api/index.ts} +197 -299
  166. package/server/app-config.ts +45 -14
  167. package/server/app-settings.ts +1 -1
  168. package/server/applets/applet-css.ts +1 -1
  169. package/server/applets/build-applet.ts +4 -4
  170. package/server/applets/build-worker.ts +3 -2
  171. package/server/applets/config.ts +1 -1
  172. package/server/{functions-worker.ts → applets/functions-worker.ts} +1 -1
  173. package/server/{functions.ts → applets/functions.ts} +3 -2
  174. package/server/applets/index.ts +2 -2
  175. package/server/{thumbnails.ts → applets/thumbnails.ts} +1 -1
  176. package/server/{applet-typecheck.ts → applets/typecheck.ts} +4 -4
  177. package/server/{ui-components.ts → applets/ui-components.ts} +2 -2
  178. package/server/applets/view-source.ts +7 -1
  179. package/server/{views.ts → applets/views.ts} +35 -46
  180. package/server/{widgets.ts → applets/widgets.ts} +2 -2
  181. package/server/cli/applet-selector.ts +19 -0
  182. package/server/cli/args.ts +5 -0
  183. package/server/{cli-colors.ts → cli/colors.ts} +1 -1
  184. package/server/cli/commands/bundle.ts +119 -0
  185. package/server/cli/commands/call-server-fn.ts +42 -0
  186. package/server/cli/commands/check.ts +53 -0
  187. package/server/cli/commands/config.ts +132 -0
  188. package/server/cli/commands/debug.ts +119 -0
  189. package/server/cli/commands/env.ts +162 -0
  190. package/server/cli/commands/hermes.ts +149 -0
  191. package/server/cli/commands/init.ts +286 -0
  192. package/server/cli/commands/navigate.ts +35 -0
  193. package/server/cli/commands/openclaw.ts +168 -0
  194. package/server/cli/commands/refresh.ts +39 -0
  195. package/server/cli/commands/scratch.ts +496 -0
  196. package/server/cli/commands/service.ts +298 -0
  197. package/server/cli/commands/skill.ts +122 -0
  198. package/server/cli/commands/start.ts +138 -0
  199. package/server/cli/commands/status.ts +80 -0
  200. package/server/cli/commands/tabs.ts +43 -0
  201. package/server/cli/commands/theme.ts +192 -0
  202. package/server/cli/commands/ui-components.ts +15 -0
  203. package/server/cli/commands/update.ts +192 -0
  204. package/server/cli/commands/version.ts +9 -0
  205. package/server/cli/commands/views.ts +87 -0
  206. package/server/cli/control.ts +89 -0
  207. package/server/{cli-env.ts → cli/env.ts} +78 -56
  208. package/server/cli/index.ts +171 -0
  209. package/server/{cli-pc.ts → cli/pc.ts} +1 -1
  210. package/server/cli/provider.ts +25 -0
  211. package/server/cli/server-version.ts +16 -0
  212. package/server/cli/server.ts +81 -0
  213. package/server/{cli-ui-components.ts → cli/ui-components.ts} +5 -5
  214. package/server/cli.ts +2 -3215
  215. package/server/collab/manager.ts +3 -3
  216. package/server/collab/skill/index.ts +2 -2
  217. package/server/control.ts +97 -78
  218. package/server/data-dir.ts +13 -0
  219. package/server/harness/README.md +55 -25
  220. package/server/harness/acp/NOTES.md +11 -11
  221. package/server/harness/acp/adapter.ts +2 -2
  222. package/server/harness/acp/archived.ts +3 -3
  223. package/server/harness/acp/client.ts +4 -3
  224. package/server/harness/acp/discovery.ts +3 -3
  225. package/server/harness/acp/run-durations.ts +1 -1
  226. package/server/harness/acp/session.ts +9 -12
  227. package/server/harness/auth.ts +303 -0
  228. package/server/harness/claude-code/NOTES.md +9 -7
  229. package/server/harness/claude-code/adapter.ts +13 -8
  230. package/server/harness/claude-code/auth.ts +127 -18
  231. package/server/harness/claude-code/cli.ts +3 -1
  232. package/server/harness/claude-code/git-worktree.ts +5 -2
  233. package/server/harness/claude-code/index.ts +7 -1
  234. package/server/harness/claude-code/mcp.ts +3 -1
  235. package/server/harness/claude-code/models.ts +2 -0
  236. package/server/harness/claude-code/session.ts +13 -39
  237. package/server/harness/claude-code/sessions.ts +8 -12
  238. package/server/harness/codex/NOTES.md +35 -16
  239. package/server/harness/codex/adapter.ts +5 -3
  240. package/server/harness/codex/auth.ts +86 -19
  241. package/server/harness/codex/client.ts +30 -34
  242. package/server/harness/codex/index.ts +20 -1
  243. package/server/harness/codex/permissions.ts +3 -3
  244. package/server/harness/codex/probe.ts +3 -5
  245. package/server/harness/codex/session.ts +20 -25
  246. package/server/harness/codex/thread-list.ts +74 -0
  247. package/server/harness/codex/transport.ts +5 -5
  248. package/server/harness/executable.ts +42 -18
  249. package/server/harness/fork.ts +12 -0
  250. package/server/harness/hermes/NOTES.md +70 -70
  251. package/server/harness/hermes/discovery.ts +1 -1
  252. package/server/harness/openclaw/NOTES.md +24 -24
  253. package/server/harness/openclaw/adapter.ts +4 -4
  254. package/server/harness/openclaw/compat.ts +1 -1
  255. package/server/harness/openclaw/session.ts +6 -31
  256. package/server/harness/registry.ts +1 -1
  257. package/server/harness/session-title.ts +12 -3
  258. package/server/harness/shell-path.ts +31 -21
  259. package/server/harness/types.ts +17 -5
  260. package/server/navigation-relay.ts +1 -1
  261. package/server/open-browser.ts +7 -0
  262. package/server/{scratchpad-assets.ts → scratchpad/assets.ts} +4 -4
  263. package/server/{scratchpad.ts → scratchpad/document.ts} +8 -8
  264. package/server/{scratchpad-executor.ts → scratchpad/executor.ts} +7 -7
  265. package/server/{scratchpad-relay.ts → scratchpad/relay.ts} +4 -5
  266. package/server/{scratchpad-shape-defaults.ts → scratchpad/shape-defaults.ts} +2 -2
  267. package/server/server-cwd.ts +1 -1
  268. package/server/service.ts +18 -4
  269. package/server/sessions/archive.ts +32 -0
  270. package/server/{attachment-message.ts → sessions/attachment-message.ts} +1 -1
  271. package/server/sessions/config.ts +41 -0
  272. package/server/sessions/lifecycle.ts +17 -0
  273. package/server/sessions/pending-views.ts +164 -0
  274. package/server/sessions/selected.ts +199 -0
  275. package/server/sessions/store.ts +127 -0
  276. package/server/sessions/view-sessions.ts +267 -0
  277. package/server/{skills-template.ts → skills/template.ts} +1 -1
  278. package/server/{skill-update.ts → skills/update.ts} +5 -5
  279. package/server/{skill-version.ts → skills/version.ts} +4 -4
  280. package/server/static.ts +1 -1
  281. package/server/status.ts +6 -4
  282. package/server/web.ts +58 -49
  283. package/server/{env-apply.ts → workspaces/env-apply.ts} +5 -5
  284. package/server/{workspace-env.ts → workspaces/env.ts} +30 -3
  285. package/server/{workspace-import.ts → workspaces/import.ts} +4 -4
  286. package/server/{workspace-init.ts → workspaces/init.ts} +10 -6
  287. package/server/{layout.ts → workspaces/layout.ts} +2 -2
  288. package/server/{preview.ts → workspaces/preview.ts} +1 -1
  289. package/server/{registry.ts → workspaces/registry.ts} +17 -7
  290. package/server/{required-env.ts → workspaces/required-env.ts} +3 -3
  291. package/server/{moi-scaffold.ts → workspaces/scaffold.ts} +4 -3
  292. package/server/{tabs.ts → workspaces/tabs.ts} +7 -10
  293. package/ui-components/button.tsx +1 -1
  294. package/ui-components/docs/attachment.md +2 -2
  295. package/ui-components/docs/button.md +1 -1
  296. package/ui-components/docs/calendar.md +1 -1
  297. package/ui-components/docs/chart.md +4 -4
  298. package/ui-components/docs/data-table.md +1 -1
  299. package/ui-components/docs/drawer.md +1 -1
  300. package/ui-components/docs/field.md +1 -1
  301. package/ui-components/docs/input.md +2 -2
  302. package/ui-components/docs/label.md +2 -2
  303. package/ui-components/docs/table.md +2 -2
  304. package/workspace/.claude/skills/moi-workspace/SKILL.md +61 -32
  305. package/workspace/.claude/skills/moi-workspace/references/COLLAB.md +4 -7
  306. package/workspace/.claude/skills/moi-workspace/references/DESIGN.md +2 -2
  307. package/workspace/.claude/skills/moi-workspace/references/INTENTS.md +2 -2
  308. package/client/features/chat/ChatPopup.tsx +0 -98
  309. package/client/features/chat/composer/banners/AgentAvailabilityBanner.tsx +0 -101
  310. package/client/features/chat/sessions/useSelectedSession.ts +0 -185
  311. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +0 -92
  312. package/client/features/overview/WorkspaceName.tsx +0 -60
  313. package/client/features/views/ViewBuilder.tsx +0 -239
  314. package/client/features/views/useViewBuilderActions.ts +0 -103
  315. package/client/features/views/useViewBuilderDrafts.ts +0 -68
  316. package/client/features/workspace/WorkspaceScreen.tsx +0 -839
  317. package/client/features/workspace/useWorkspaceNavigation.ts +0 -203
  318. package/dist/chunk-2jncyq65.js +0 -1
  319. package/dist/chunk-e2q5ken7.js +0 -68
  320. package/dist/chunk-h2kj1ysj.js +0 -1
  321. package/dist/chunk-jf6czgrz.js +0 -2
  322. package/dist/chunk-nez8sdta.js +0 -1
  323. package/dist/chunk-nzwgm8vc.css +0 -1
  324. package/dist/chunk-ph0h6h86.js +0 -1
  325. package/dist/chunk-ryg9z3kn.js +0 -10
  326. package/dist/chunk-tpn177bt.js +0 -2
  327. package/lib/view-builder-directives.ts +0 -16
  328. package/server/agent.ts +0 -223
  329. package/server/chat-selection.ts +0 -22
  330. package/server/selected-session.ts +0 -152
  331. package/server/session-config.ts +0 -136
  332. package/server/view-builders.ts +0 -453
  333. /package/client/components/shared/{AgentBlobatar.tsx → agent-blobatar.tsx} +0 -0
  334. /package/client/components/shared/{BottomPanel.tsx → bottom-panel.tsx} +0 -0
  335. /package/client/components/shared/{Composer.tsx → composer.tsx} +0 -0
  336. /package/client/components/shared/{LedLogo.tsx → led-logo.tsx} +0 -0
  337. /package/client/components/shared/{PanelHeader.tsx → panel-header.tsx} +0 -0
  338. /package/client/components/shared/{ReorderableList.tsx → reorderable-list.tsx} +0 -0
  339. /package/client/components/shared/{WorkspaceIcon.tsx → workspace-icon.tsx} +0 -0
  340. /package/client/features/applets/{WidgetErrorBoundary.tsx → widget-error-boundary.tsx} +0 -0
  341. /package/client/features/chat/composer/attachments/{AttachmentChip.tsx → attachment-chip.tsx} +0 -0
  342. /package/client/features/chat/messages/{ChatPromptBubbles.tsx → chat-prompt-bubbles.tsx} +0 -0
  343. /package/client/features/chat/messages/{ShimmerText.tsx → shimmer-text.tsx} +0 -0
  344. /package/client/features/chat/messages/tool-group/{CodeBlock.tsx → code-block.tsx} +0 -0
  345. /package/client/features/chat/messages/tool-group/{Collapse.tsx → collapse.tsx} +0 -0
  346. /package/client/features/chat/messages/{useStickToBottom.ts → use-stick-to-bottom.ts} +0 -0
  347. /package/client/features/connectors/{IconMcp.tsx → icon-mcp.tsx} +0 -0
  348. /package/client/features/dev/{BlobatarShapesPage.tsx → blobatar-shapes-page.tsx} +0 -0
  349. /package/client/features/dev/{HarnessDebugPage.tsx → harness-debug-page.tsx} +0 -0
  350. /package/client/features/dev/{TextureLabPage.tsx → texture-lab-page.tsx} +0 -0
  351. /package/client/features/dev/{ToolCallsPage.tsx → tool-calls-page.tsx} +0 -0
  352. /package/client/features/drawings/{DrawingLayer.tsx → drawing-layer.tsx} +0 -0
  353. /package/client/features/home/{WorkspacePreview.tsx → workspace-preview.tsx} +0 -0
  354. /package/client/features/overview/{useGridReconcile.ts → use-grid-reconcile.ts} +0 -0
  355. /package/client/features/scratchpad/{ScratchpadControls.tsx → scratchpad-controls.tsx} +0 -0
  356. /package/client/features/settings/{SettingsLayout.tsx → settings-layout.tsx} +0 -0
  357. /package/client/features/update/{UpdateControl.tsx → update-control.tsx} +0 -0
  358. /package/client/features/workspace/{UnavailablePage.tsx → unavailable-page.tsx} +0 -0
  359. /package/client/features/workspace/{useFitsSplitLayout.ts → use-fits-split-layout.ts} +0 -0
  360. /package/client/features/workspace/{WorkspaceContext.tsx → workspace-context.tsx} +0 -0
  361. /package/client/features/workspace/{WorkspaceLayoutContext.tsx → workspace-layout-context.tsx} +0 -0
  362. /package/server/{bundle-queue.ts → applets/bundle-queue.ts} +0 -0
  363. /package/server/{applet-log.ts → applets/log.ts} +0 -0
  364. /package/server/{cli-ui.ts → cli/ui.ts} +0 -0
  365. /package/server/{workspace-config.ts → workspaces/config.ts} +0 -0
  366. /package/server/{icon.ts → workspaces/icon.ts} +0 -0
  367. /package/server/{theme.ts → workspaces/theme.ts} +0 -0
package/server/cli.ts CHANGED
@@ -1,3216 +1,3 @@
1
1
  #!/usr/bin/env bun
2
- import './cli-colors' // must precede citty: sets NO_COLOR before its color flag is computed
3
- import { defineCommand, runMain, showUsage } from 'citty'
4
- import { formatHex } from 'culori'
5
- import { parse as devalueParse } from 'devalue'
6
- import { existsSync } from 'node:fs'
7
- import { tmpdir } from 'node:os'
8
- import { dirname, join, resolve } from 'path'
9
- import pc from './cli-pc'
10
-
11
- import { isAgentCaller } from './agent-caller'
12
- import { getAppConfig, initializeAppConfig } from './app-config'
13
-
14
- import { appletSelectorMatches, parseAppletSelector } from '@/lib/applet-selector'
15
- import type { AppletSelector } from '@/lib/applet-selector'
16
- import {
17
- AGENT_THEMES,
18
- COLOR_THEMES,
19
- DEFAULT_WORKSPACE_THEME,
20
- FONT_THEMES,
21
- RADIUS_THEMES,
22
- deriveThemeColors
23
- } from '@/lib/themes'
24
- import type { AgentTheme, ColorTheme, FontTheme, RadiusTheme } from '@/lib/themes'
25
- import { parseMoiHref } from '@/lib/navigation'
26
- import { EXPERIMENTAL_FEATURES, experimentalFlagName } from '@/lib/experimental'
27
- import type { ExperimentalFeatures } from '@/lib/experimental'
28
- import type {
29
- AppletLogEntry,
30
- ScratchArrowEnd,
31
- ScratchColor,
32
- ScratchFill,
33
- ScratchImageQuality,
34
- ScratchOp,
35
- ScratchSize,
36
- ScratchStyle,
37
- WorkspaceEntry,
38
- WorkspaceSkillStatus,
39
- WorkspaceType
40
- } from '@/lib/types'
41
-
42
- import {
43
- execWithEnv,
44
- notifyEnvChanged,
45
- readSecretValue,
46
- renderEnvView,
47
- resolveCwdWorkspace
48
- } from './cli-env'
49
- import { columns, keyValue } from './cli-ui'
50
- import { installCollabSkill } from './collab/skill'
51
- import { CONTROL_HOST, CONTROL_PORT, CONTROL_URL, PORT } from './constants'
52
- import { type ControlProbe, controlFailureMessage, probeControlServer } from './control-client'
53
- import {
54
- HARNESS_TYPES,
55
- type DetectedAgent,
56
- agentBindingFor,
57
- detectHarness,
58
- harnessLabel,
59
- isHarnessName
60
- } from './harness/detect'
61
- import {
62
- type HermesProfile,
63
- discoverHermesProfiles,
64
- matchHermesProfile
65
- } from './harness/hermes/discovery'
66
- import { type OpenClawAgent, discoverOpenClawAgents } from './harness/openclaw/discovery'
67
- import {
68
- assertWorkspaceIdAvailable,
69
- liftToWorkspaceRoot,
70
- listWorkspaces,
71
- registerWorkspace
72
- } from './registry'
73
- import { serverCwd } from './server-cwd'
74
- import {
75
- isBehind,
76
- isMinorBehind,
77
- resolveWorkspace,
78
- skillStatuses,
79
- staleSkillNotice
80
- } from './skill-version'
81
- import { updateWorkspaceSkills } from './skill-update'
82
- import {
83
- ServiceError,
84
- analyzeInstall,
85
- captureServiceEnv,
86
- installService,
87
- queryServerInfo,
88
- restartService,
89
- serviceLogPath,
90
- serviceStatus,
91
- uninstallService
92
- } from './service'
93
- import {
94
- detectPackageManager,
95
- fetchLatestVersion,
96
- installedBinVersion,
97
- isNewer,
98
- manualUpdateLines,
99
- runPackageManager,
100
- superviseServerUpdates,
101
- updateArgv
102
- } from './update'
103
- import { VERSION, isPrerelease, versionWithCommit } from './version'
104
- import {
105
- getWorkspaceEnvView,
106
- isValidEnvKey,
107
- secretBackend,
108
- updateWorkspaceEnv
109
- } from './workspace-env'
110
- import { provisionWorkspace } from './workspace-init'
111
-
112
- // ---- helpers ----------------------------------------------------------------
113
-
114
- async function isServerRunning(): Promise<boolean> {
115
- return (await probeControlServer()).status === 'running'
116
- }
117
-
118
- // Print why the control socket could not be opened, then exit. Classifies the
119
- // failure first, so "no server is listening" and "the server is up but the
120
- // address is unreachable" no longer read as the same problem.
121
- async function exitControlUnreachable(): Promise<never> {
122
- console.error(controlFailureMessage(await probeControlServer()))
123
- process.exit(1)
124
- }
125
-
126
- async function waitForServer(timeoutMs = 10_000): Promise<boolean> {
127
- const deadline = Date.now() + timeoutMs
128
- while (Date.now() < deadline) {
129
- if (await isServerRunning()) return true
130
- await Bun.sleep(200)
131
- }
132
- return false
133
- }
134
-
135
- async function registerViaControl(absPath: string): Promise<string> {
136
- return new Promise((res, rej) => {
137
- const ws = new WebSocket(CONTROL_URL)
138
- ws.onopen = () => ws.send(JSON.stringify({ type: 'workspace:register', path: absPath }))
139
- ws.onmessage = event => {
140
- const data = JSON.parse(String(event.data))
141
- if (data.id) {
142
- ws.close()
143
- res(data.id)
144
- }
145
- }
146
- ws.onerror = () => void probeControlServer().then(p => rej(new Error(controlFailureMessage(p))))
147
- })
148
- }
149
-
150
- async function openBrowser(url: string) {
151
- try {
152
- if (process.platform === 'darwin') await Bun.$`open ${url}`.quiet()
153
- else if (process.platform === 'linux') await Bun.$`xdg-open ${url}`.quiet()
154
- } catch {}
155
- }
156
-
157
- // Spawn the server as a child. MOI_SERVER=1 tells the child it is the actual
158
- // server process. No `--hot`: frontend HMR comes from Bun.serve's dev bundler,
159
- // and server reloads are a full process restart driven by the dev supervisor
160
- // (see runDevSupervisor).
161
- function spawnServer(
162
- cwd: string,
163
- env: Record<string, string | undefined> = process.env,
164
- experimentalFlags: string[] = []
165
- ): ReturnType<typeof Bun.spawn> {
166
- const argv = ['bun', import.meta.filename, 'start', ...experimentalFlags]
167
- return Bun.spawn(argv, {
168
- stdin: 'inherit',
169
- stdout: 'inherit',
170
- stderr: 'inherit',
171
- cwd,
172
- env: {
173
- ...env,
174
- MOI_SERVER: '1'
175
- }
176
- })
177
- }
178
-
179
- // Dev supervisor: run the server as a child WITHOUT `bun --hot`, watch the
180
- // server-side source (`server/`, `lib/`) and full-restart the child on change.
181
- // Client files are intentionally not watched here — Bun.serve owns frontend HMR
182
- // and patches the browser in place. The child shuts down gracefully on SIGTERM
183
- // (closing servers + killing function workers), so restarts leak nothing.
184
- async function runDevSupervisor(
185
- projectRoot: string,
186
- env: Record<string, string | undefined>,
187
- experimentalFlags: string[]
188
- ): Promise<void> {
189
- const { watch } = await import('node:fs')
190
-
191
- let child = spawnServer(projectRoot, env, experimentalFlags)
192
- let restarting = false
193
- let debounce: ReturnType<typeof setTimeout> | undefined
194
-
195
- async function restart(reason: string) {
196
- if (restarting) return
197
- restarting = true
198
- console.log(pc.dim(`\n↻ ${reason} — restarting server…`))
199
- try {
200
- child.kill('SIGTERM')
201
- } catch {}
202
- const sigkill = setTimeout(() => {
203
- try {
204
- child.kill('SIGKILL')
205
- } catch {}
206
- }, 3000)
207
- await child.exited
208
- clearTimeout(sigkill)
209
- restarting = false
210
- child = spawnServer(projectRoot, env, experimentalFlags)
211
- }
212
-
213
- for (const dir of ['server', 'lib']) {
214
- watch(join(projectRoot, dir), { recursive: true }, (_event, file) => {
215
- if (!file || !file.endsWith('.ts')) return
216
- clearTimeout(debounce)
217
- debounce = setTimeout(() => restart(`${file} changed`), 100)
218
- })
219
- }
220
-
221
- // Forward termination to the child, then exit the supervisor.
222
- for (const sig of ['SIGINT', 'SIGTERM'] as const) {
223
- process.on(sig, () => {
224
- try {
225
- child.kill('SIGTERM')
226
- } catch {}
227
- process.exit(0)
228
- })
229
- }
230
-
231
- // Keep the supervisor alive indefinitely.
232
- await new Promise<void>(() => {})
233
- }
234
-
235
- // ---- commands ---------------------------------------------------------------
236
-
237
- // `moi init`'s harness decision: an explicit `--harness` wins, otherwise
238
- // auto-detection (harness/detect.ts). Exits when neither settles it — silently
239
- // defaulting to Claude Code would install skills into `.claude/skills/` for an
240
- // agent that reads from somewhere else entirely, which fails later and quietly.
241
- async function resolveInitHarness(
242
- target: string,
243
- requested: string | undefined
244
- ): Promise<{ type: WorkspaceType; agent: DetectedAgent | null }> {
245
- if (requested !== undefined) {
246
- const value = requested.trim()
247
- if (!isHarnessName(value)) {
248
- console.error('\n' + pc.red('✗') + ' Unknown harness: ' + pc.bold(requested))
249
- console.error(pc.dim(' Valid values: ' + HARNESS_TYPES.join(', ')) + '\n')
250
- process.exit(1)
251
- }
252
- // An explicit choice still picks up the agent binding when the provider
253
- // can confirm it. It often can't — OpenClaw needs a running gateway — so a
254
- // miss warns rather than blocking a deliberate override.
255
- const agent = await agentBindingFor(value, target)
256
- if (!agent && (value === 'openclaw' || value === 'hermes')) {
257
- const noun = value === 'hermes' ? 'profile' : 'agent'
258
- console.log(
259
- '\n' +
260
- pc.yellow('⚠') +
261
- ' No ' +
262
- harnessLabel[value] +
263
- ' ' +
264
- noun +
265
- ' found at this path — registering without one.\n' +
266
- pc.dim(' Run ') +
267
- pc.bold('moi ' + value + ' init') +
268
- pc.dim(' to bind it once ' + harnessLabel[value] + ' can see the workspace.')
269
- )
270
- }
271
- return { type: value, agent }
272
- }
273
-
274
- // A registered workspace has already answered this question, and may carry no
275
- // on-disk signal at all (a folder created from the UI whose agent has never
276
- // run in it), so the registry outranks detection when re-running `moi init`
277
- // to refresh skills.
278
- const known = (await listWorkspaces()).find(e => e.path === target)
279
- if (known) {
280
- const type = known.type ?? 'claude-code'
281
- console.log(
282
- '\n' + pc.dim(' Already registered — initializing for ') + pc.bold(harnessLabel[type])
283
- )
284
- return {
285
- type,
286
- agent: known.agentId
287
- ? {
288
- agentId: known.agentId,
289
- ...(known.name ? { name: known.name } : {}),
290
- isDefault: known.isDefault ?? false,
291
- ...(known.lastRunAt ? { lastRunAt: known.lastRunAt } : {})
292
- }
293
- : null
294
- }
295
- }
296
-
297
- const detected = await detectHarness(target)
298
- if (detected) {
299
- console.log(
300
- '\n' +
301
- pc.yellow('◆') +
302
- ' Detected ' +
303
- detected.reason +
304
- ' — initializing for ' +
305
- pc.bold(harnessLabel[detected.type]) +
306
- '.'
307
- )
308
- return { type: detected.type, agent: detected.agent ?? null }
309
- }
310
-
311
- console.error('\n' + pc.red('✗') + ' No agent harness detected in ' + pc.bold(target))
312
- console.error(
313
- pc.dim(' Looked for a Hermes profile, an OpenClaw agent, and Codex or Claude Code history.\n')
314
- )
315
- console.error(' Pick one:\n')
316
- console.error(
317
- keyValue(
318
- HARNESS_TYPES.map(t => [pc.bold('moi init --harness=' + t), harnessLabel[t]]),
319
- ' '
320
- )
321
- )
322
- console.error()
323
- process.exit(1)
324
- }
325
-
326
- const init = defineCommand({
327
- meta: {
328
- name: 'init',
329
- description: 'Initialize workspace, copy skills and scaffold folder with widgets'
330
- },
331
- args: {
332
- dir: {
333
- type: 'positional',
334
- default: '.',
335
- description: 'Target directory (default: current)'
336
- },
337
- harness: {
338
- type: 'string',
339
- description: 'Agent harness: ' + HARNESS_TYPES.join(', ') + ' (default: auto-detect)'
340
- },
341
- web: {
342
- type: 'boolean',
343
- default: false,
344
- description: 'Start the web server if not already running'
345
- },
346
- 'experimental-collab': {
347
- type: 'boolean',
348
- default: false,
349
- description: 'Include the optional collaboration guide and applet types'
350
- },
351
- id: {
352
- type: 'string',
353
- description:
354
- 'Register under this id instead of a generated one — fails if the workspace is already registered'
355
- }
356
- },
357
- async run({ args }) {
358
- const requested = resolve(args.dir)
359
- // Locate the workspace root first: if invoked from inside a `.moi/` (or a
360
- // deeper accidental `.moi/.moi/…`), lift to the directory that owns it
361
- // instead of scaffolding a nested workspace. This is what stops the
362
- // `.moi/.moi` bug at the source.
363
- const target = liftToWorkspaceRoot(requested)
364
- if (target !== requested) {
365
- console.log(
366
- '\n' +
367
- pc.yellow('◆') +
368
- ' Ran inside ' +
369
- pc.bold('.moi') +
370
- ' — using the workspace root ' +
371
- pc.bold(target) +
372
- ' instead (no nested .moi created).'
373
- )
374
- }
375
- // Flag a stray nested `.moi/.moi` left by the old cwd bug — harmless but
376
- // confusing, and easy to remove.
377
- const stray = join(target, '.moi', '.moi')
378
- if (existsSync(stray)) {
379
- console.log(
380
- '\n' +
381
- pc.yellow('⚠') +
382
- ' Found a stray nested ' +
383
- pc.bold('.moi/.moi') +
384
- ' (from an older bug). Safe to remove:\n' +
385
- pc.dim(' rm -rf ' + stray)
386
- )
387
- }
388
-
389
- // A chosen id is only assignable at first registration, so refuse it here —
390
- // before any skills are copied or `.moi/` is scaffolded.
391
- if (args.id) {
392
- try {
393
- await assertWorkspaceIdAvailable(target, args.id)
394
- } catch (err) {
395
- console.error('\n' + pc.red('✗') + ' ' + (err as Error).message + '\n')
396
- process.exit(1)
397
- }
398
- }
399
-
400
- const projectRoot = join(import.meta.dir, '..')
401
- const isInteractive = process.stdout.isTTY
402
-
403
- // Which backend this workspace is for has to be settled before
404
- // provisioning: each harness reads skills from a different directory, and
405
- // agent-owned ones (OpenClaw, Hermes) need their agent metadata on the
406
- // registry entry — same as `moi <provider> init`.
407
- const { type, agent } = await resolveInitHarness(target, args.harness)
408
-
409
- // Provision: bundled skills + the `.moi/` bootstrap (widgets dir +
410
- // package.json + bun install). An existing `.moi/` is left untouched.
411
- console.log()
412
- const { scaffold, skillsDir, installLogPath } = await provisionWorkspace(target, type)
413
- if (args['experimental-collab']) {
414
- const { referencePath } = await installCollabSkill(target, type)
415
- console.log(pc.dim(' Collaboration guide installed to ' + referencePath))
416
- console.log(pc.dim(' Live presence requires moi start --experimental-collab'))
417
- }
418
- if (scaffold !== 'exists') {
419
- if (scaffold === 'installing') {
420
- console.log(pc.dim(' Widget dependencies still installing in .moi/ (background)'))
421
- console.log(pc.dim(' Install log: ' + installLogPath))
422
- } else if (scaffold === 0) {
423
- console.log(pc.dim(' Installed widget dependencies in .moi/'))
424
- } else {
425
- console.warn(
426
- pc.yellow(` bun install failed (exit ${scaffold}) — run it manually in .moi/`)
427
- )
428
- console.warn(pc.dim(' Install log: ' + installLogPath))
429
- }
430
- }
431
-
432
- // Always register the workspace in the persistent registry
433
- const entry = await registerWorkspace(target, {
434
- ...(args.id ? { id: args.id } : {}),
435
- type,
436
- ...(agent
437
- ? {
438
- name: agent.name,
439
- agentId: agent.agentId,
440
- isDefault: agent.isDefault,
441
- lastRunAt: agent.lastRunAt
442
- }
443
- : {})
444
- })
445
-
446
- console.log(pc.green('✓') + ' Initialized ' + pc.bold(target) + pc.dim(' (' + type + ')'))
447
- console.log(
448
- ' Skills installed to ' +
449
- pc.dim(skillsDir) +
450
- ' — ask ' +
451
- (type === 'claude-code' ? 'Claude' : 'your agent') +
452
- ' to build a widget or a view to get started\n'
453
- )
454
-
455
- // If --web and server not running, start it (stay alive as wrapper)
456
- let running = await isServerRunning()
457
-
458
- if (!running && args.web) {
459
- console.log(pc.dim(' Starting server…'))
460
- const cwd = serverCwd(projectRoot, false)
461
- const proc = spawnServer(cwd)
462
- running = await waitForServer()
463
- if (!running) {
464
- console.error(pc.red(' Server failed to start\n'))
465
- await proc.exited
466
- process.exit(1)
467
- }
468
- const url = `http://localhost:${PORT}/workspace/${entry.id}`
469
- console.log(pc.green('✓') + ' Server started on http://localhost:' + PORT)
470
- if (isInteractive) console.log(' Opening ' + pc.bold(url))
471
- console.log(pc.dim(' Press Ctrl+C to stop\n'))
472
- if (isInteractive) await openBrowser(url)
473
- process.exit(await superviseServerUpdates(proc, () => spawnServer(cwd)))
474
- }
475
-
476
- if (running) {
477
- // Server already running — notify it and open (browser only in interactive mode)
478
- await registerViaControl(target)
479
- const url = `http://localhost:${PORT}/workspace/${entry.id}`
480
- if (isInteractive) {
481
- console.log(' Opening ' + pc.bold(url) + '\n')
482
- await openBrowser(url)
483
- } else {
484
- console.log(' Ready at ' + pc.bold(url) + '\n')
485
- }
486
- process.exit(0)
487
- }
488
-
489
- // Server not running and --web not passed
490
- console.log(' Run ' + pc.bold('moi start') + ' to open in the browser\n')
491
- }
492
- })
493
-
494
- const experimentalArgs = Object.fromEntries(
495
- EXPERIMENTAL_FEATURES.map(feature => {
496
- const name = experimentalFlagName(feature)
497
- const label = name.slice('experimental-'.length).replaceAll('-', ' ')
498
- return [name, { type: 'boolean' as const, description: `Enable experimental ${label}` }]
499
- })
500
- )
501
-
502
- const start = defineCommand({
503
- meta: { name: 'start', description: 'Start the moi web server' },
504
- args: {
505
- port: {
506
- type: 'string',
507
- description: 'HTTP port to listen on (default: 13337)'
508
- },
509
- ...experimentalArgs
510
- },
511
- async run({ args, rawArgs }) {
512
- const knownFlags = new Set(EXPERIMENTAL_FEATURES.map(experimentalFlagName))
513
- for (const arg of rawArgs) {
514
- if (arg.startsWith('--experimental-') && !knownFlags.has(arg.slice(2))) {
515
- throw new Error(`Unknown experimental feature: ${arg.slice('--experimental-'.length)}`)
516
- }
517
- }
518
- const experimental: Partial<ExperimentalFeatures> = {}
519
- const experimentalFlags: string[] = []
520
- for (const feature of EXPERIMENTAL_FEATURES) {
521
- const flag = experimentalFlagName(feature)
522
- if (args[flag] !== true) continue
523
- experimental[feature] = true
524
- experimentalFlags.push(`--${flag}`)
525
- }
526
- const projectRoot = join(import.meta.dir, '..')
527
- // Undocumented: --dev runs the watch-and-full-restart dev supervisor.
528
- const dev = process.argv.includes('--dev')
529
- // Undocumented: --debug turns on the messaging trace (MOI_DEBUG) in the
530
- // server — console lines for each message/session/turn in the chat pipeline.
531
- const debug = process.argv.includes('--debug')
532
-
533
- // Launcher path: we are the CLI, not the server. Decide whether to bail
534
- // (a server is already up), run the dev supervisor, or spawn a one-shot
535
- // server. Skipped when MOI_SERVER=1 (we are the spawned server itself).
536
- if (!process.env.MOI_SERVER) {
537
- if (await isServerRunning()) {
538
- // Say who owns the running server: a service-managed one is expected
539
- // to be here, and `moi service` is how to manage it.
540
- const info = await queryServerInfo()
541
- const port = info?.port || PORT
542
- if (info?.service) {
543
- console.log(
544
- '\n' +
545
- pc.yellow('◆') +
546
- ' The moi service is already running on http://localhost:' +
547
- port +
548
- pc.dim(` (v${info.version})`) +
549
- '\n' +
550
- pc.dim(' Manage it with `moi service` — restart, logs, uninstall.') +
551
- '\n'
552
- )
553
- } else {
554
- console.log(
555
- '\n' + pc.yellow('◆') + ' Server is already running on http://localhost:' + port + '\n'
556
- )
557
- }
558
- process.exit(0)
559
- }
560
-
561
- // Spawn server with correct cwd so bunfig.toml is picked up at Bun startup.
562
- // MOI_DEV tells the server to use the live bundler + HMR even if a stale
563
- // `dist/` exists in the tree (prod serves prebuilt `dist/` statically).
564
- const env = {
565
- ...process.env,
566
- // The dev bundler snapshots process.env at server startup, so the
567
- // PUBLIC_* inlining (bunfig `[serve.static] env`) only sees vars that
568
- // are set before the server process spawns — setting one later from
569
- // server code does nothing. Default the tldraw key here so an unset
570
- // key inlines as '' (→ watermark) instead of leaving a bare
571
- // `process.env.…` in the browser bundle that throws.
572
- PUBLIC_TLDRAW_LICENSE_KEY: process.env.PUBLIC_TLDRAW_LICENSE_KEY ?? '',
573
- ...(args.port ? { PORT: args.port } : {}),
574
- ...(dev ? { MOI_DEV: '1' } : {}),
575
- ...(debug ? { MOI_DEBUG: '1' } : {})
576
- }
577
- if (dev) {
578
- await runDevSupervisor(projectRoot, env, experimentalFlags)
579
- return
580
- }
581
- const cwd = serverCwd(projectRoot, dev)
582
- const proc = spawnServer(cwd, env, experimentalFlags)
583
- process.exit(
584
- await superviseServerUpdates(proc, () => spawnServer(cwd, env, experimentalFlags))
585
- )
586
- }
587
-
588
- // This IS the server process (MOI_SERVER=1). cwd is the package root when the
589
- // dev bundler runs (bunfig loaded at Bun startup) or a neutral dir for a
590
- // prebuilt install — see serverCwd().
591
- initializeAppConfig(experimental)
592
- try {
593
- await import('./web')
594
- } catch (err) {
595
- // Startup failure (port taken, config error). Under the service manager
596
- // exit 0 on purpose: launchd (KeepAlive.SuccessfulExit=false) and
597
- // systemd (Restart=on-failure) both read a clean exit as "do not
598
- // respawn", so a permanently-broken start idles instead of looping.
599
- const code = (err as { code?: string })?.code
600
- if (code === 'EADDRINUSE') {
601
- console.error(
602
- `\n${pc.red('✗')} Port already in use (http :${PORT} / control :${CONTROL_PORT}) — ` +
603
- 'is another moi server running?'
604
- )
605
- } else {
606
- console.error(`\n${pc.red('✗')} Server failed to start: ${String(err)}`)
607
- }
608
- if (process.env.MOI_SERVICE) {
609
- console.error(pc.dim(' The service stays idle — fix this, then `moi service restart`.\n'))
610
- process.exit(0)
611
- }
612
- process.exit(1)
613
- }
614
- console.log(`\n${pc.green('✓')} Server started on http://localhost:${PORT}`)
615
- console.log(pc.dim(' Press Ctrl+C to stop\n'))
616
- // Stay alive as the server
617
- }
618
- })
619
-
620
- function colorStatus(status: string) {
621
- if (status === 'built') return pc.green(status)
622
- if (status === 'failed') return pc.red(status)
623
- return pc.dim(status)
624
- }
625
-
626
- const appletOnlyArg = {
627
- type: 'string' as const,
628
- description: 'Limit to "widgets", "views", "widgets/<id>", or "views/<id>"'
629
- }
630
-
631
- function readAppletSelector(value: string | undefined): AppletSelector | undefined {
632
- if (value === undefined) return undefined
633
- if (parseAppletSelector(value)) return value as AppletSelector
634
- console.error(
635
- '\n' +
636
- pc.red('✗') +
637
- ` Invalid --only value "${value}" — use "widgets", "views", "widgets/<id>", or "views/<id>".\n`
638
- )
639
- process.exit(1)
640
- }
641
-
642
- const bundle = defineCommand({
643
- meta: { name: 'bundle', description: 'Rebuild changed widgets and views' },
644
- args: {
645
- dir: {
646
- type: 'positional',
647
- default: '.',
648
- description: 'Workspace directory (default: current)'
649
- },
650
- force: {
651
- type: 'boolean',
652
- description: 'Rebuild the selected applets, ignoring file modification times',
653
- default: false
654
- },
655
- only: appletOnlyArg,
656
- status: {
657
- type: 'boolean',
658
- description: 'Advance a view builder to ready on success (use --no-status to skip)',
659
- default: true
660
- }
661
- },
662
- async run({ args }) {
663
- const only = readAppletSelector(args.only)
664
- const path = resolve(args.dir)
665
- // Computed locally up front so it can ride along in the success output; the
666
- // agent reads this and knows to run `moi skill update`.
667
- const notice = await staleSkillNotice(path)
668
- const ws = new WebSocket(CONTROL_URL)
669
-
670
- ws.onopen = () =>
671
- ws.send(
672
- JSON.stringify({
673
- type: 'bundle',
674
- path,
675
- force: args.force,
676
- only,
677
- noStatus: !args.status
678
- })
679
- )
680
-
681
- ws.onmessage = event => {
682
- const res = JSON.parse(String(event.data))
683
-
684
- // The server fails loudly when the path isn't inside a registered
685
- // workspace (e.g. run from an unrelated dir) instead of silently no-op'ing.
686
- if (res.error) {
687
- console.error('\n' + pc.red(pc.bold('Error:')) + ' ' + res.error + '\n')
688
- ws.close()
689
- process.exit(1)
690
- }
691
-
692
- type Row = { kind?: string; name: string; status: string; error?: string }
693
- const results: Row[] = Array.isArray(res.results) ? res.results : []
694
- const where = typeof res.workspacePath === 'string' ? res.workspacePath : path
695
-
696
- // Empty here means a *real* workspace with no widgets/views — not the old
697
- // "wrong dir" footgun (that's an error above now). Say so plainly.
698
- if (results.length === 0) {
699
- console.log(
700
- '\n' +
701
- pc.bold('moi bundle') +
702
- pc.dim(' — nothing to build') +
703
- '\n\n' +
704
- pc.dim(` No widgets or views found in ${where}/.moi/`) +
705
- '\n'
706
- )
707
- if (notice) console.log(pc.yellow(notice) + '\n')
708
- ws.close()
709
- process.exit(0)
710
- }
711
-
712
- const counts: Record<string, number> = {}
713
- for (const r of results) counts[r.status] = (counts[r.status] ?? 0) + 1
714
- const summary = ['built', 'skipped', 'failed']
715
- .filter(s => counts[s])
716
- .map(s => `${counts[s]} ${s}`)
717
- .join(' · ')
718
-
719
- console.log('\n' + pc.bold('moi bundle') + pc.dim(` — ${summary}`) + '\n')
720
- console.log(
721
- columns(
722
- ['kind', 'name', 'status'].map(h => pc.dim(h)),
723
- results.map(r => [pc.dim(r.kind ?? ''), r.name, colorStatus(r.status)])
724
- )
725
- )
726
-
727
- const failed = results.filter(r => r.status === 'failed')
728
- console.log()
729
- for (const f of failed) {
730
- console.log(pc.red(pc.bold(f.name + ':')))
731
- console.log(' ' + f.error + '\n')
732
- }
733
-
734
- // Runtime errors still standing after the rebuild's clear-on-success
735
- // sweep — point the agent at the journal while it's paying attention.
736
- const logCount = typeof res.logCount === 'number' ? res.logCount : 0
737
- if (logCount > 0) {
738
- console.log(
739
- pc.yellow(`ℹ ${logCount} applet runtime error(s) on record — run \`moi debug logs\`.`) +
740
- '\n'
741
- )
742
- }
743
-
744
- if (notice) console.log(pc.yellow(notice) + '\n')
745
- ws.close()
746
- process.exit(failed.length > 0 ? 1 : 0)
747
- }
748
-
749
- ws.onerror = () => void exitControlUnreachable()
750
- }
751
- })
752
-
753
- const check = defineCommand({
754
- meta: { name: 'check', description: 'Run applet checks' },
755
- args: {
756
- dir: {
757
- type: 'positional',
758
- default: '.',
759
- description: 'Workspace directory (default: current)'
760
- },
761
- only: appletOnlyArg
762
- },
763
- async run({ args }) {
764
- const only = readAppletSelector(args.only)
765
- const { root } = await resolveWorkspace(resolve(args.dir))
766
- if (!existsSync(join(root, '.moi'))) {
767
- console.error('\n' + pc.red('✗') + ` No moi workspace found at ${root}\n`)
768
- process.exit(1)
769
- }
770
- const { formatAppletTypecheckDiagnostics, typecheckApplets } =
771
- await import('./applet-typecheck')
772
- const result = await typecheckApplets(root, only)
773
-
774
- if (only?.includes('/') && result.files.length === 0) {
775
- console.error('\n' + pc.red('✗') + ` Applet "${only}" not found.\n`)
776
- process.exit(1)
777
- }
778
-
779
- if (result.diagnostics.length > 0) {
780
- console.error('\n' + pc.red('✗') + ' Applet check failed: TypeScript\n')
781
- console.error(formatAppletTypecheckDiagnostics(result.diagnostics))
782
- process.exit(1)
783
- }
784
-
785
- if (result.files.length === 0) {
786
- const scope = args.only ? `.moi/${args.only}` : '.moi/widgets or .moi/views'
787
- console.log('\n' + pc.green('✓') + ` No applet source files found in ${scope}\n`)
788
- return
789
- }
790
-
791
- const suffix = only ? ` (${only})` : ''
792
- console.log(
793
- '\n' +
794
- pc.green('✓') +
795
- ` Applet checks passed: TypeScript · ${result.files.length} file${result.files.length === 1 ? '' : 's'}${suffix}\n`
796
- )
797
- }
798
- })
799
-
800
- const builderSet = defineCommand({
801
- meta: { name: 'set', description: 'Set a view or widget builder id, status, title, and icon' },
802
- args: {
803
- id: { type: 'positional', required: true, description: 'View or widget id' },
804
- dir: {
805
- type: 'positional',
806
- default: '.',
807
- description: 'Workspace directory (default: current)'
808
- },
809
- kind: { type: 'string', default: 'view', description: '"view" or "widget"' },
810
- status: { type: 'string', description: 'Report build state: "building" or "waiting"' },
811
- title: { type: 'string', description: 'Display title' },
812
- icon: { type: 'string', description: 'App icon registry id' },
813
- builder: {
814
- type: 'string',
815
- description: 'Builder handle for a pending view builder (from its request)'
816
- }
817
- },
818
- run({ args }) {
819
- const path = resolve(args.dir)
820
- const ws = new WebSocket(CONTROL_URL)
821
- ws.onopen = () =>
822
- ws.send(
823
- JSON.stringify({
824
- type: 'builder:set',
825
- path,
826
- id: args.id,
827
- kind: args.kind,
828
- status: args.status,
829
- title: args.title,
830
- icon: args.icon,
831
- builder: args.builder
832
- })
833
- )
834
- ws.onmessage = event => {
835
- const result = JSON.parse(String(event.data))
836
- if (result.error) {
837
- console.error('\n' + pc.red(pc.bold('Error:')) + ' ' + result.error + '\n')
838
- ws.close()
839
- process.exit(1)
840
- }
841
- console.log(
842
- '\n' +
843
- pc.green('✓') +
844
- ' Builder set ' +
845
- pc.bold(String(result.builder?.viewId ?? args.id)) +
846
- '\n'
847
- )
848
- ws.close()
849
- process.exit(0)
850
- }
851
- ws.onerror = () => void exitControlUnreachable()
852
- }
853
- })
854
-
855
- const builder = defineCommand({
856
- meta: { name: 'builder', description: 'Manage a view or widget builder' },
857
- subCommands: { set: builderSet }
858
- })
859
-
860
- const refresh = defineCommand({
861
- meta: {
862
- name: 'refresh',
863
- description:
864
- 'Refresh widget and view data without rebuilding. Use after the agent mutates underlying data.'
865
- },
866
- args: {
867
- only: appletOnlyArg
868
- },
869
- async run({ args }) {
870
- const only = readAppletSelector(args.only)
871
- const notice = await staleSkillNotice(process.cwd())
872
- const ws = new WebSocket(CONTROL_URL)
873
-
874
- ws.onopen = () => ws.send(JSON.stringify({ type: 'applets:refresh', only }))
875
-
876
- ws.onmessage = event => {
877
- const data = JSON.parse(String(event.data))
878
- if (data.error) {
879
- console.error('\n' + pc.red('✗') + ' ' + data.error + '\n')
880
- ws.close()
881
- process.exit(1)
882
- }
883
- console.log('\n' + pc.green('✓') + ' Refresh signal sent' + (only ? ` (${only})` : '') + '\n')
884
- if (notice) console.log(pc.yellow(notice) + '\n')
885
- ws.close()
886
- process.exit(0)
887
- }
888
-
889
- ws.onerror = () => void exitControlUnreachable()
890
- }
891
- })
892
-
893
- function swatchHexToRgb(hex: string): [number, number, number] {
894
- const value = Number.parseInt(hex.slice(1), 16)
895
- return [(value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff]
896
- }
897
-
898
- // Truecolor swatch using raw ANSI 24-bit escapes (picocolors maxes at 8 colors).
899
- // Falls back to blank spaces when stdout is not a TTY, keeping piped output clean.
900
- function swatch(bg?: string, fg?: string): string {
901
- if (!process.stdout.isTTY || !bg) return ' '
902
- const [br, bgg, bb] = swatchHexToRgb(bg)
903
- const [fr, fgg, fb] = swatchHexToRgb(fg ?? '#000000')
904
- return `\x1b[48;2;${br};${bgg};${bb}m\x1b[38;2;${fr};${fgg};${fb}m Aa \x1b[0m`
905
- }
906
-
907
- function themeSwatch(primary?: string): string {
908
- if (!primary) return swatch()
909
- const colors = deriveThemeColors(primary)
910
- return swatch(formatHex(colors.primary), formatHex(colors.primaryForeground))
911
- }
912
-
913
- const theme = defineCommand({
914
- meta: { name: 'theme', description: 'Show or set the workspace appearance' },
915
- args: {
916
- dir: {
917
- type: 'positional',
918
- default: '.',
919
- description: 'Workspace directory (default: current)'
920
- },
921
- font: { type: 'string', description: 'Font theme key to apply' },
922
- color: { type: 'string', description: 'Color preset key to apply' },
923
- radius: { type: 'string', description: 'Radius preset key to apply' },
924
- agent: { type: 'string', description: 'Agent preset key to apply' }
925
- },
926
- async run({ args }) {
927
- const path = resolve(args.dir)
928
- const notice = await staleSkillNotice(path)
929
- const ws = new WebSocket(CONTROL_URL)
930
-
931
- ws.onopen = () =>
932
- ws.send(
933
- JSON.stringify({
934
- type: 'theme',
935
- path,
936
- font: args.font ?? null,
937
- color: args.color ?? null,
938
- radius: args.radius ?? null,
939
- agent: args.agent ?? null
940
- })
941
- )
942
-
943
- ws.onmessage = event => {
944
- const res = JSON.parse(String(event.data))
945
-
946
- if (res.error) {
947
- console.error('\n' + pc.red(pc.bold('Error:')) + ' ' + res.error + '\n')
948
- ws.close()
949
- process.exit(1)
950
- }
951
-
952
- if (res.ok) {
953
- console.log()
954
- if (res.font) {
955
- const config = FONT_THEMES[res.font as FontTheme]
956
- console.log(
957
- pc.green('✓') +
958
- ' Font set to ' +
959
- pc.bold(config.label) +
960
- pc.dim(` (${config.sans} / ${config.mono})`)
961
- )
962
- }
963
- if (res.color) {
964
- const preset = COLOR_THEMES[res.color as ColorTheme]
965
- const chip = themeSwatch(preset.primary)
966
- console.log(pc.green('✓') + ' Color set to ' + pc.bold(preset.label) + ' ' + chip)
967
- }
968
- if (res.radius) {
969
- const preset = RADIUS_THEMES[res.radius as RadiusTheme]
970
- console.log(pc.green('✓') + ' Radius set to ' + pc.bold(preset.label))
971
- }
972
- if (res.agent) {
973
- const preset = AGENT_THEMES[res.agent as AgentTheme]
974
- console.log(pc.green('✓') + ' Agent set to ' + pc.bold(preset.label))
975
- }
976
- console.log()
977
- if (notice) console.log(pc.yellow(notice) + '\n')
978
- ws.close()
979
- process.exit(0)
980
- }
981
-
982
- const currentFont: FontTheme = res.currentFont ?? DEFAULT_WORKSPACE_THEME.font
983
- const currentColor: ColorTheme = res.currentColor ?? DEFAULT_WORKSPACE_THEME.color
984
- const currentRadius: RadiusTheme = res.currentRadius ?? DEFAULT_WORKSPACE_THEME.radius
985
- const currentAgent: AgentTheme = res.currentAgent ?? DEFAULT_WORKSPACE_THEME.agent
986
- console.log('\n' + pc.bold('moi theme') + ' — workspace appearance')
987
- console.log(
988
- pc.dim(' Usage: moi theme --font=<key> --color=<key> --radius=<key> --agent=<key>') + '\n'
989
- )
990
-
991
- const fontRows = (Object.keys(FONT_THEMES) as FontTheme[]).map(key => {
992
- const f = FONT_THEMES[key]
993
- const selected = key === currentFont
994
- return [
995
- selected ? pc.green('→') : ' ',
996
- selected ? pc.bold(key) : key,
997
- f.label,
998
- pc.dim(f.sans),
999
- pc.dim(f.mono)
1000
- ]
1001
- })
1002
- console.log(pc.dim(' Fonts'))
1003
- console.log(
1004
- columns(
1005
- ['', 'key', 'label', 'sans', 'mono'].map(h => pc.dim(h)),
1006
- fontRows
1007
- ) + '\n'
1008
- )
1009
-
1010
- const colorRows = (Object.keys(COLOR_THEMES) as ColorTheme[]).map(key => {
1011
- const c = COLOR_THEMES[key]
1012
- const selected = key === currentColor
1013
- return [
1014
- selected ? pc.green('→') : ' ',
1015
- selected ? pc.bold(key) : key,
1016
- c.label,
1017
- themeSwatch(c.primary)
1018
- ]
1019
- })
1020
- console.log(pc.dim(' Colors'))
1021
- console.log(
1022
- columns(
1023
- ['', 'key', 'label', 'swatch'].map(h => pc.dim(h)),
1024
- colorRows
1025
- ) + '\n'
1026
- )
1027
-
1028
- const radiusRows = (Object.keys(RADIUS_THEMES) as RadiusTheme[]).map(key => {
1029
- const radius = RADIUS_THEMES[key]
1030
- const selected = key === currentRadius
1031
- return [
1032
- selected ? pc.green('→') : ' ',
1033
- selected ? pc.bold(key) : key,
1034
- radius.label,
1035
- pc.dim(radius.radius)
1036
- ]
1037
- })
1038
- console.log(pc.dim(' Radius'))
1039
- console.log(
1040
- columns(
1041
- ['', 'key', 'label', 'value'].map(h => pc.dim(h)),
1042
- radiusRows
1043
- ) + '\n'
1044
- )
1045
-
1046
- const agentRows = (Object.keys(AGENT_THEMES) as AgentTheme[]).map(key => {
1047
- const agent = AGENT_THEMES[key]
1048
- const selected = key === currentAgent
1049
- return [selected ? pc.green('→') : ' ', selected ? pc.bold(key) : key, agent.label]
1050
- })
1051
- console.log(pc.dim(' Agent'))
1052
- console.log(
1053
- columns(
1054
- ['', 'key', 'label'].map(h => pc.dim(h)),
1055
- agentRows
1056
- ) + '\n'
1057
- )
1058
-
1059
- if (notice) console.log(pc.yellow(notice) + '\n')
1060
- ws.close()
1061
- process.exit(0)
1062
- }
1063
-
1064
- ws.onerror = () => void exitControlUnreachable()
1065
- }
1066
- })
1067
-
1068
- // The CLI-vs-server freshness check, shared by `moi status` and `moi update`:
1069
- // compares this CLI's version against what the running server reports over the
1070
- // control port. Works no matter how the upgrade happened (`moi update` or a
1071
- // manual package-manager install) — the comparison reads live state, it does
1072
- // not live inside the update command.
1073
- function versionMismatchNotice(serverVersion: string): string | null {
1074
- if (serverVersion === VERSION) return null
1075
- return (
1076
- pc.yellow('⚠') +
1077
- ` Server is running v${serverVersion}, this CLI is v${VERSION}.\n` +
1078
- pc.dim(' Restart to match: `moi service restart` (service) or Ctrl-C + `moi start`.')
1079
- )
1080
- }
1081
-
1082
- const status = defineCommand({
1083
- meta: { name: 'status', description: 'Show server status and registered workspaces' },
1084
- async run() {
1085
- const probe: ControlProbe = await probeControlServer()
1086
- const notice = await staleSkillNotice(process.cwd())
1087
-
1088
- if (probe.status === 'not-running') {
1089
- console.log('\n' + pc.dim('○') + ' Server is ' + pc.bold('not running'))
1090
- console.log(pc.dim(` cli version ${VERSION}`) + '\n')
1091
- process.exit(0)
1092
- }
1093
-
1094
- // The dial failed for a reason other than an empty port, so the server may
1095
- // be up and healthy. Name the real obstacle instead of blaming the process.
1096
- if (probe.status === 'unreachable') {
1097
- console.log('\n' + pc.yellow('◆') + ' Server is ' + pc.bold('unreachable'))
1098
- console.log(pc.dim(` control port ${CONTROL_HOST}:${CONTROL_PORT} — ${probe.reason}`))
1099
- console.log(pc.dim(` cli version ${VERSION}`) + '\n')
1100
- process.exit(1)
1101
- }
1102
-
1103
- const info = await queryServerInfo()
1104
- console.log(
1105
- '\n' +
1106
- pc.green('●') +
1107
- ' Server is ' +
1108
- pc.bold('running') +
1109
- pc.dim(
1110
- ` (http port: ${info?.port || PORT}, control port: ${CONTROL_PORT}` +
1111
- (info?.pid ? `, pid: ${info.pid}` : '') +
1112
- ')'
1113
- )
1114
- )
1115
- if (info) {
1116
- console.log(
1117
- pc.dim(` server version ${info.version}`) +
1118
- (info.service ? pc.dim(' · service-managed (`moi service`)') : '')
1119
- )
1120
- }
1121
- console.log(pc.dim(` cli version ${VERSION}`))
1122
- const mismatch = info ? versionMismatchNotice(info.version) : null
1123
- if (mismatch) console.log('\n' + mismatch)
1124
-
1125
- await new Promise<void>((resolve, reject) => {
1126
- const ws = new WebSocket(CONTROL_URL)
1127
-
1128
- ws.onopen = () => ws.send(JSON.stringify({ type: 'workspace:list' }))
1129
-
1130
- ws.onmessage = event => {
1131
- const res = JSON.parse(String(event.data))
1132
- const workspaces: WorkspaceEntry[] = res.workspaces ?? []
1133
- const n = workspaces.length
1134
- console.log(pc.dim(` ${n} workspace${n === 1 ? '' : 's'} registered\n`))
1135
-
1136
- ws.close()
1137
- resolve()
1138
- }
1139
-
1140
- ws.onerror = () =>
1141
- void probeControlServer().then(p => reject(new Error(controlFailureMessage(p))))
1142
- })
1143
-
1144
- if (notice) console.log(pc.yellow(notice) + '\n')
1145
- process.exit(0)
1146
- }
1147
- })
1148
-
1149
- // ---- env subcommands --------------------------------------------------------
1150
-
1151
- function envFail(message: string): never {
1152
- console.error('\n' + pc.red('✗') + ' ' + message + '\n')
1153
- process.exit(1)
1154
- }
1155
-
1156
- const envSet = defineCommand({
1157
- meta: {
1158
- name: 'set',
1159
- description:
1160
- 'Set custom secrets: `moi env set KEY=value [KEY=value...]`, or `moi env set KEY` to read one value from stdin'
1161
- },
1162
- args: {
1163
- key: {
1164
- type: 'positional',
1165
- required: true,
1166
- description: 'KEY=value pair(s), or a single bare KEY to read the value from stdin'
1167
- }
1168
- },
1169
- async run({ args }) {
1170
- const entry = await resolveCwdWorkspace()
1171
- const pairs = args._
1172
- const set: Record<string, string> = {}
1173
-
1174
- if (pairs.length === 1 && !pairs[0].includes('=')) {
1175
- // Bare-KEY form: one key, value from stdin (hidden prompt on a TTY).
1176
- const key = pairs[0]
1177
- if (!isValidEnvKey(key)) envFail(`Invalid env key: ${key}`)
1178
- let value: string
1179
- try {
1180
- value = await readSecretValue(key)
1181
- } catch {
1182
- // Ctrl-C at the hidden prompt.
1183
- process.exit(1)
1184
- }
1185
- // An empty value is almost always an unset variable on the piping side —
1186
- // storing '' would silently shadow a real .env value with nothing.
1187
- if (value === '')
1188
- envFail(`Empty value for ${key} — pipe a non-empty value or pass ${key}=value`)
1189
- set[key] = value
1190
- } else {
1191
- for (const pair of pairs) {
1192
- const eq = pair.indexOf('=')
1193
- if (eq === -1) {
1194
- envFail(
1195
- `Missing value for ${pair} — use KEY=value (bare KEY reads stdin only when set alone)`
1196
- )
1197
- }
1198
- const key = pair.slice(0, eq)
1199
- const value = pair.slice(eq + 1)
1200
- if (!isValidEnvKey(key)) envFail(`Invalid env key: ${key}`)
1201
- if (value === '')
1202
- envFail(`Empty value for ${key} — use \`moi env unset ${key}\` to remove a key`)
1203
- set[key] = value
1204
- }
1205
- }
1206
-
1207
- await updateWorkspaceEnv(entry.path, { set })
1208
- await notifyEnvChanged(entry.path)
1209
- for (const key of Object.keys(set)) {
1210
- console.log(pc.green('✓') + ` Set ${pc.bold(key)} ${pc.dim('(custom)')}`)
1211
- }
1212
- // A plaintext fallback should never go unnoticed at write time.
1213
- if ((await secretBackend()) === 'file') {
1214
- console.log(pc.dim(' Stored in a 0600 file — OS keychain unavailable.'))
1215
- }
1216
- process.exit(0)
1217
- }
1218
- })
1219
-
1220
- const envUnset = defineCommand({
1221
- meta: { name: 'unset', description: 'Remove custom secrets: `moi env unset KEY [KEY...]`' },
1222
- args: {
1223
- key: { type: 'positional', required: true, description: 'Key(s) to remove' }
1224
- },
1225
- async run({ args }) {
1226
- const entry = await resolveCwdWorkspace()
1227
- const view = await getWorkspaceEnvView(entry.path)
1228
- const byKey = new Map(view.vars.map(v => [v.key, v]))
1229
-
1230
- // Only custom secrets are removable; a dotenv-sourced key lives in its file.
1231
- const removable: string[] = []
1232
- let hadError = false
1233
- for (const key of args._) {
1234
- const v = byKey.get(key)
1235
- if (!v) {
1236
- console.warn(pc.yellow('!') + ` ${key} is not set — skipping`)
1237
- continue
1238
- }
1239
- if (v.source === 'dotenv') {
1240
- console.error(
1241
- pc.red('✗') +
1242
- ` ${key} comes from ${(v.files ?? []).join(', ')} — edit that file instead` +
1243
- pc.dim(' (moi env unset only removes custom secrets)')
1244
- )
1245
- hadError = true
1246
- continue
1247
- }
1248
- removable.push(key)
1249
- }
1250
-
1251
- if (removable.length > 0) {
1252
- await updateWorkspaceEnv(entry.path, { remove: removable })
1253
- await notifyEnvChanged(entry.path)
1254
- for (const key of removable) {
1255
- const v = byKey.get(key)
1256
- const unshadow =
1257
- v?.source === 'both' ? pc.dim(` (falls back to ${(v.files ?? []).join(', ')})`) : ''
1258
- console.log(pc.green('✓') + ` Removed ${pc.bold(key)}${unshadow}`)
1259
- }
1260
- }
1261
- process.exit(hadError ? 1 : 0)
1262
- }
1263
- })
1264
-
1265
- const envExec = defineCommand({
1266
- meta: {
1267
- name: 'exec',
1268
- description: 'Run a command with the workspace env: `moi env exec -- <cmd> [args...]`'
1269
- },
1270
- async run({ rawArgs }) {
1271
- // Everything after `--` is the child command, untouched by flag parsing.
1272
- const sep = rawArgs.indexOf('--')
1273
- const cmd = sep === -1 ? [] : rawArgs.slice(sep + 1)
1274
- if (cmd.length === 0) {
1275
- console.error('\n' + pc.red('✗') + ' Usage: moi env exec -- <cmd> [args...]\n')
1276
- process.exit(1)
1277
- }
1278
- const entry = await resolveCwdWorkspace()
1279
- process.exit(await execWithEnv(entry.path, cmd))
1280
- }
1281
- })
1282
-
1283
- const envSubCommands = { set: envSet, unset: envUnset, exec: envExec }
1284
-
1285
- const env = defineCommand({
1286
- meta: {
1287
- name: 'env',
1288
- description: 'Show the workspace env (key names only — never values)'
1289
- },
1290
- subCommands: envSubCommands,
1291
- async run({ rawArgs }) {
1292
- // citty invokes the parent run even after dispatching a subcommand — only
1293
- // render the table when no subcommand ran. Object.hasOwn so prototype
1294
- // names ('constructor', 'toString') never count as a dispatched command.
1295
- const first = rawArgs.find(a => !a.startsWith('-'))
1296
- if (first && Object.hasOwn(envSubCommands, first)) return
1297
- const entry = await resolveCwdWorkspace()
1298
- // Lazy: required-env pulls the widget/view bundler chain (TS compiler),
1299
- // which must not load for every other `moi` command's startup.
1300
- const { requiredEnvFor } = await import('./required-env')
1301
- const view = await getWorkspaceEnvView(entry.path, requiredEnvFor(entry.path))
1302
- console.log('\n' + renderEnvView(entry, view) + '\n')
1303
- process.exit(0)
1304
- }
1305
- })
1306
-
1307
- // ---- provider commands (openclaw / hermes) ----------------------------------
1308
-
1309
- // `moi <provider>` on its own lists the commands AND what they can be run
1310
- // against, so discovering the installable agents never requires `init`.
1311
- function printProviderCommands(provider: string, argHint: string) {
1312
- console.log('\n' + pc.bold(' Commands'))
1313
- console.log(
1314
- keyValue(
1315
- [
1316
- [
1317
- pc.bold(`moi ${provider} init`) + ' ' + pc.dim(argHint),
1318
- 'Install moi skills and register the workspace'
1319
- ]
1320
- ],
1321
- ' '
1322
- )
1323
- )
1324
- }
1325
-
1326
- // The argument is optional when there is exactly one candidate, so the hint
1327
- // should not demand one that isn't needed.
1328
- function initHint(provider: string, count: number, label: string): string {
1329
- return count === 1 ? `moi ${provider} init` : `moi ${provider} init <${label}>`
1330
- }
1331
-
1332
- // ---- openclaw subcommands ---------------------------------------------------
1333
-
1334
- // Match an `agent` argument against `agentId` (exact) or `name`
1335
- // (case-insensitive). Returns the matching agent or null.
1336
- function findAgent(agents: OpenClawAgent[], query: string): OpenClawAgent | null {
1337
- const exact = agents.find(a => a.agentId === query)
1338
- if (exact) return exact
1339
- const q = query.toLowerCase()
1340
- return agents.find(a => a.name?.toLowerCase() === q) ?? null
1341
- }
1342
-
1343
- function printAgentTable(agents: OpenClawAgent[]) {
1344
- console.log(
1345
- columns(
1346
- ['', 'agentId', 'name', 'workspace'].map(h => pc.dim(h)),
1347
- agents.map(a => [
1348
- a.isDefault ? pc.green('●') : ' ',
1349
- a.isDefault ? pc.bold(a.agentId) : a.agentId,
1350
- a.name ?? pc.dim('—'),
1351
- pc.dim(a.path)
1352
- ])
1353
- )
1354
- )
1355
- }
1356
-
1357
- const openclawInit = defineCommand({
1358
- meta: {
1359
- name: 'init',
1360
- description:
1361
- 'Install moi skills into an OpenClaw agent workspace. Run without args to list discovered agents.'
1362
- },
1363
- args: {
1364
- agent: {
1365
- type: 'positional',
1366
- required: false,
1367
- description: 'Agent id or name (omit to list agents)'
1368
- }
1369
- },
1370
- async run({ args }) {
1371
- const agents = await discoverOpenClawAgents()
1372
- if (agents.length === 0) {
1373
- console.error(
1374
- '\n' +
1375
- pc.red('✗') +
1376
- ' No OpenClaw agents discovered.\n' +
1377
- pc.dim(
1378
- ' Make sure the OpenClaw gateway is running and ~/.openclaw/openclaw.json is set.\n'
1379
- )
1380
- )
1381
- process.exit(1)
1382
- }
1383
-
1384
- // No argument: with a single agent there is nothing to choose, so install
1385
- // into it. Only an ambiguous choice needs the list.
1386
- if (!args.agent && agents.length > 1) {
1387
- console.log('\n' + pc.bold('OpenClaw agents'))
1388
- console.log(
1389
- pc.dim(' Run ' + pc.bold('moi openclaw init <agentId>') + ' to install skills.\n')
1390
- )
1391
- printAgentTable(agents)
1392
- console.log()
1393
- process.exit(0)
1394
- }
1395
-
1396
- const target = args.agent ? findAgent(agents, args.agent) : agents[0]
1397
- if (!target) {
1398
- console.error('\n' + pc.red('✗') + ' Agent not found: ' + pc.bold(args.agent) + '\n')
1399
- console.log(' Available:\n')
1400
- printAgentTable(agents)
1401
- console.log()
1402
- process.exit(1)
1403
- }
1404
-
1405
- // Shared provisioning path with `moi init`: skills land in
1406
- // <agent-workspace>/skills/<name>/ (OpenClaw resolves <workspace>/skills
1407
- // with the highest precedence, so these win over any same-named bundled or
1408
- // per-user skill), plus the `.moi/` bootstrap — the widgets skill assumes
1409
- // the folder and its dependencies exist. Existing `.moi/` stays untouched.
1410
- const {
1411
- scaffold,
1412
- skillsDir: skillsRoot,
1413
- installLogPath
1414
- } = await provisionWorkspace(target.path, 'openclaw')
1415
- if (scaffold !== 'exists') {
1416
- if (scaffold === 'installing') {
1417
- console.log('\n' + pc.dim(' Widget dependencies still installing in .moi/ (background)'))
1418
- console.log(pc.dim(' Install log: ' + installLogPath))
1419
- } else if (scaffold === 0) {
1420
- console.log('\n' + pc.dim(' Installed widget dependencies in .moi/'))
1421
- } else {
1422
- console.warn(
1423
- '\n' + pc.yellow(` bun install failed (exit ${scaffold}) — run it manually in .moi/`)
1424
- )
1425
- console.warn(pc.dim(' Install log: ' + installLogPath))
1426
- }
1427
- }
1428
-
1429
- // Register in the moi registry so the agent's workspace appears in the
1430
- // UI workspace list. Mirrors what `moi init` does for Claude Code.
1431
- const entry = await registerWorkspace(target.path, {
1432
- type: 'openclaw',
1433
- name: target.name,
1434
- agentId: target.agentId,
1435
- isDefault: target.isDefault,
1436
- lastRunAt: target.lastRunAt
1437
- })
1438
-
1439
- console.log('\n' + pc.green('✓') + ' Installed skills to ' + pc.bold(skillsRoot))
1440
- console.log(
1441
- pc.dim(' Agent: ') +
1442
- pc.bold(target.agentId) +
1443
- (target.name ? pc.dim(' (' + target.name + ')') : '')
1444
- )
1445
- const isInteractive = process.stdout.isTTY
1446
- const running = await isServerRunning()
1447
- if (running) {
1448
- const url = `http://localhost:${PORT}/workspace/${entry.id}`
1449
- // Notify the running server so it picks up the new entry without a
1450
- // restart, then open (browser only in interactive mode) — same shape
1451
- // as `moi init`'s already-running branch.
1452
- await registerViaControl(target.path)
1453
- if (isInteractive) {
1454
- console.log(' Opening ' + pc.bold(url) + '\n')
1455
- await openBrowser(url)
1456
- } else {
1457
- console.log(' Ready at ' + pc.bold(url) + '\n')
1458
- }
1459
- } else {
1460
- console.log(' Run ' + pc.bold('moi start') + ' to open in the browser\n')
1461
- }
1462
- process.exit(0)
1463
- }
1464
- })
1465
-
1466
- const openclaw = defineCommand({
1467
- meta: { name: 'openclaw', description: 'OpenClaw integration commands' },
1468
- async run({ rawArgs }) {
1469
- // citty runs the parent even after dispatching a subcommand — the bare
1470
- // form is the only one this handles.
1471
- if (rawArgs.some(arg => !arg.startsWith('-'))) return
1472
- console.log('\n' + pc.bold('OpenClaw'))
1473
- printProviderCommands('openclaw', '[agent]')
1474
- const agents = await discoverOpenClawAgents().catch(() => [])
1475
- if (agents.length === 0) {
1476
- console.log(
1477
- '\n ' +
1478
- pc.dim('No agents discovered — start the OpenClaw gateway and check ') +
1479
- pc.dim('~/.openclaw/openclaw.json') +
1480
- '\n'
1481
- )
1482
- return
1483
- }
1484
- console.log('\n' + pc.bold(' Agents'))
1485
- printAgentTable(agents)
1486
- console.log(pc.dim('\n Run ') + pc.bold(initHint('openclaw', agents.length, 'agentId')) + '\n')
1487
- },
1488
- subCommands: { init: openclawInit }
1489
- })
1490
-
1491
- // ---- hermes subcommands -----------------------------------------------------
1492
-
1493
- function printProfileTable(profiles: HermesProfile[]) {
1494
- console.log(
1495
- columns(
1496
- ['', 'profile', 'model', 'workspace'].map(h => pc.dim(h)),
1497
- profiles.map(p => [
1498
- p.isDefault ? pc.green('●') : ' ',
1499
- p.isDefault ? pc.bold(p.agentId) : p.agentId,
1500
- p.model ?? pc.dim('—'),
1501
- pc.dim(p.path)
1502
- ])
1503
- )
1504
- )
1505
- }
1506
-
1507
- const hermesInit = defineCommand({
1508
- meta: {
1509
- name: 'init',
1510
- description:
1511
- 'Install moi skills into a Hermes profile workspace. Run without args to list discovered profiles.'
1512
- },
1513
- args: {
1514
- profile: {
1515
- type: 'positional',
1516
- required: false,
1517
- description: 'Profile id or description (omit to list profiles)'
1518
- }
1519
- },
1520
- async run({ args }) {
1521
- const profiles = await discoverHermesProfiles()
1522
- if (profiles.length === 0) {
1523
- console.error(
1524
- '\n' +
1525
- pc.red('✗') +
1526
- ' No Hermes profiles discovered.\n' +
1527
- pc.dim(' Install Hermes and run ' + pc.bold('hermes setup') + ' first.\n')
1528
- )
1529
- process.exit(1)
1530
- }
1531
-
1532
- // No argument: with a single profile there is nothing to choose, so
1533
- // install into it. Only an ambiguous choice needs the list.
1534
- if (!args.profile && profiles.length > 1) {
1535
- console.log('\n' + pc.bold('Hermes profiles'))
1536
- console.log(pc.dim(' Run ' + pc.bold('moi hermes init <profile>') + ' to install skills.\n'))
1537
- printProfileTable(profiles)
1538
- console.log()
1539
- process.exit(0)
1540
- }
1541
-
1542
- const target = args.profile ? matchHermesProfile(profiles, args.profile) : profiles[0]
1543
- if (!target) {
1544
- console.error('\n' + pc.red('✗') + ' Profile not found: ' + pc.bold(args.profile) + '\n')
1545
- console.log(' Available:\n')
1546
- printProfileTable(profiles)
1547
- console.log()
1548
- process.exit(1)
1549
- }
1550
-
1551
- // Shared provisioning path with `moi init`: skills land in
1552
- // <profile>/workspace/skills/<name>/ (Hermes resolves the workspace skills
1553
- // dir with the highest precedence, so these win over bundled ones), plus
1554
- // the `.moi/` bootstrap. The default profile has no workspace directory
1555
- // until now — provisionWorkspace creates it.
1556
- const {
1557
- scaffold,
1558
- skillsDir: skillsRoot,
1559
- installLogPath
1560
- } = await provisionWorkspace(target.path, 'hermes')
1561
- if (scaffold !== 'exists') {
1562
- if (scaffold === 'installing') {
1563
- console.log('\n' + pc.dim(' Widget dependencies still installing in .moi/ (background)'))
1564
- console.log(pc.dim(' Install log: ' + installLogPath))
1565
- } else if (scaffold === 0) {
1566
- console.log('\n' + pc.dim(' Installed widget dependencies in .moi/'))
1567
- } else {
1568
- console.warn(
1569
- '\n' + pc.yellow(` bun install failed (exit ${scaffold}) — run it manually in .moi/`)
1570
- )
1571
- console.warn(pc.dim(' Install log: ' + installLogPath))
1572
- }
1573
- }
1574
-
1575
- const entry = await registerWorkspace(target.path, {
1576
- type: 'hermes',
1577
- name: target.name,
1578
- agentId: target.agentId,
1579
- isDefault: target.isDefault
1580
- })
1581
-
1582
- console.log('\n' + pc.green('✓') + ' Installed skills to ' + pc.bold(skillsRoot))
1583
- console.log(
1584
- pc.dim(' Profile: ') +
1585
- pc.bold(target.agentId) +
1586
- (target.model ? pc.dim(' (' + target.model + ')') : '')
1587
- )
1588
- const isInteractive = process.stdout.isTTY
1589
- const running = await isServerRunning()
1590
- if (running) {
1591
- const url = `http://localhost:${PORT}/workspace/${entry.id}`
1592
- await registerViaControl(target.path)
1593
- if (isInteractive) {
1594
- console.log(' Opening ' + pc.bold(url) + '\n')
1595
- await openBrowser(url)
1596
- } else {
1597
- console.log(' Ready at ' + pc.bold(url) + '\n')
1598
- }
1599
- } else {
1600
- console.log(' Run ' + pc.bold('moi start') + ' to open in the browser\n')
1601
- }
1602
- process.exit(0)
1603
- }
1604
- })
1605
-
1606
- const hermes = defineCommand({
1607
- meta: { name: 'hermes', description: 'Hermes Agent integration commands' },
1608
- async run({ rawArgs }) {
1609
- // citty runs the parent even after dispatching a subcommand — the bare
1610
- // form is the only one this handles.
1611
- if (rawArgs.some(arg => !arg.startsWith('-'))) return
1612
- console.log('\n' + pc.bold('Hermes'))
1613
- printProviderCommands('hermes', '[profile]')
1614
- const profiles = await discoverHermesProfiles().catch(() => [])
1615
- if (profiles.length === 0) {
1616
- console.log(
1617
- '\n ' +
1618
- pc.dim('No profiles discovered — install Hermes and run ') +
1619
- pc.dim('hermes setup') +
1620
- '\n'
1621
- )
1622
- return
1623
- }
1624
- console.log('\n' + pc.bold(' Profiles'))
1625
- printProfileTable(profiles)
1626
- console.log(pc.dim('\n Run ') + pc.bold(initHint('hermes', profiles.length, 'profile')) + '\n')
1627
- },
1628
- subCommands: { init: hermesInit }
1629
- })
1630
-
1631
- async function sendConfig(payload: {
1632
- path: string
1633
- name?: string
1634
- iconPath?: string
1635
- clearName?: boolean
1636
- clearIcon?: boolean
1637
- }) {
1638
- const notice = await staleSkillNotice(payload.path)
1639
- const ws = new WebSocket(CONTROL_URL)
1640
- ws.onopen = () => ws.send(JSON.stringify({ type: 'config', ...payload }))
1641
- ws.onmessage = event => {
1642
- const res = JSON.parse(String(event.data))
1643
- if (res.error) {
1644
- console.error('\n' + pc.red(pc.bold('Error:')) + ' ' + res.error + '\n')
1645
- ws.close()
1646
- process.exit(1)
1647
- }
1648
- console.log()
1649
- if (res.ok) {
1650
- if (res.clearedName) console.log(pc.green('✓') + ' Name reset to ' + pc.dim('(folder name)'))
1651
- else if (res.name) console.log(pc.green('✓') + ' Name set to ' + pc.bold(res.name))
1652
- if (res.clearedIcon)
1653
- console.log(pc.green('✓') + ' Icon reset to ' + pc.dim('default (provider)'))
1654
- else if (res.icon) console.log(pc.green('✓') + ' Icon updated ' + pc.dim('(128×128 webp)'))
1655
- } else {
1656
- console.log(pc.bold('moi config') + ' — workspace identity\n')
1657
- console.log(
1658
- ' ' + pc.dim('name') + ' ' + (res.name ? pc.bold(res.name) : pc.dim('(folder name)'))
1659
- )
1660
- console.log(
1661
- ' ' +
1662
- pc.dim('icon') +
1663
- ' ' +
1664
- (res.hasIcon ? pc.green('custom') : pc.dim('default (provider)'))
1665
- )
1666
- }
1667
- console.log()
1668
- if (notice) console.log(pc.yellow(notice) + '\n')
1669
- ws.close()
1670
- process.exit(0)
1671
- }
1672
- ws.onerror = () => void exitControlUnreachable()
1673
- }
1674
-
1675
- // A terse cheat sheet — one line per command — so an agent can grasp the
1676
- // surface at a glance instead of parsing citty's full ARGUMENTS/OPTIONS dump.
1677
- function printConfigHelp() {
1678
- const row = (cmd: string, desc: string) => ' ' + pc.cyan(cmd.padEnd(34)) + pc.dim(desc)
1679
- console.log()
1680
- console.log(pc.bold('moi config') + pc.dim(' — workspace name & icon'))
1681
- console.log()
1682
- console.log(row('moi config', 'Show current name & icon'))
1683
- console.log(row('moi config name "My WS"', 'Set the display name'))
1684
- console.log(row('moi config name --clear', 'Reset name to folder default'))
1685
- console.log(row('moi config icon ./logo.png', 'Set icon (png/jpg/gif/webp → 128×128 webp)'))
1686
- console.log(row('moi config icon --clear', 'Reset icon to provider default'))
1687
- console.log(row(' --dir <path>', 'Target workspace (default: current dir)'))
1688
- console.log()
1689
- }
1690
-
1691
- const config = defineCommand({
1692
- meta: {
1693
- name: 'config',
1694
- description: 'Show or set the workspace name and icon (moi config [name|icon] <value>)'
1695
- },
1696
- args: {
1697
- field: {
1698
- type: 'positional',
1699
- required: false,
1700
- description: '"name" or "icon" — omit to show the current config'
1701
- },
1702
- value: {
1703
- type: 'positional',
1704
- required: false,
1705
- description: 'The new name, or a path to an image file (png/jpg/gif/webp)'
1706
- },
1707
- clear: {
1708
- type: 'boolean',
1709
- description: 'Reset the field to its default (folder name / provider icon)'
1710
- },
1711
- dir: { type: 'string', default: '.', description: 'Workspace directory (default: current)' }
1712
- },
1713
- run({ args }) {
1714
- const path = resolve(args.dir)
1715
- if (args.field === 'help') {
1716
- printConfigHelp()
1717
- return
1718
- }
1719
- if (!args.field) {
1720
- sendConfig({ path })
1721
- return
1722
- }
1723
- if (args.field === 'name') {
1724
- if (args.clear) {
1725
- sendConfig({ path, clearName: true })
1726
- return
1727
- }
1728
- if (!args.value) {
1729
- console.error(pc.red('Usage:') + ' moi config name "<workspace name>"')
1730
- process.exit(1)
1731
- }
1732
- sendConfig({ path, name: args.value })
1733
- } else if (args.field === 'icon') {
1734
- if (args.clear) {
1735
- sendConfig({ path, clearIcon: true })
1736
- return
1737
- }
1738
- if (!args.value) {
1739
- console.error(pc.red('Usage:') + ' moi config icon <path-to-image>')
1740
- process.exit(1)
1741
- }
1742
- sendConfig({ path, iconPath: resolve(args.value) })
1743
- } else {
1744
- console.error(
1745
- pc.red(`Unknown field "${args.field}".`) +
1746
- ' Use ' +
1747
- pc.bold('name') +
1748
- ' or ' +
1749
- pc.bold('icon') +
1750
- '.'
1751
- )
1752
- process.exit(1)
1753
- }
1754
- }
1755
- })
1756
-
1757
- // ---- scratch (Scratchpad canvas) --------------------------------------------
1758
-
1759
- // Parse a "x,y" coordinate pair (tldraw canvas space, y down).
1760
- function parseXY(s: string): { x: number; y: number } {
1761
- const parts = s.split(',').map(p => Number(p.trim()))
1762
- if (parts.length !== 2 || !parts.every(n => Number.isFinite(n))) {
1763
- throw new Error(`Expected "x,y", got "${s}"`)
1764
- }
1765
- return { x: parts[0], y: parts[1] }
1766
- }
1767
-
1768
- // An arrow endpoint: a bare "x,y" is a free point; anything else is a shape name
1769
- // to bind to (so the arrow follows that shape).
1770
- function parseEnd(s: string): ScratchArrowEnd {
1771
- if (/^-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?$/.test(s)) return parseXY(s)
1772
- return { name: s }
1773
- }
1774
-
1775
- // The Scratchpad palette (matches the UI toolbar's six swatches) and each color's
1776
- // light-theme solid hex — used to snap an arbitrary `--color #rrggbb` to the nearest
1777
- // palette entry (tldraw shapes can't hold free hex). Keep in sync with the swatches
1778
- // in client/components/Scratchpad.tsx.
1779
- const COLOR_HEX: Record<ScratchColor, string> = {
1780
- black: '#1d1d1d',
1781
- red: '#e03131',
1782
- yellow: '#f1ac4b',
1783
- green: '#099268',
1784
- blue: '#4465e9',
1785
- grey: '#9fa8b2'
1786
- }
1787
- const COLOR_NAMES = Object.keys(COLOR_HEX) as ScratchColor[]
1788
-
1789
- // Arrows expose tldraw's size as a line weight; the CLI mirrors the UI's two sizes.
1790
- const STROKE_SIZES: Record<string, ScratchSize> = { small: 'm', large: 'xl' }
1791
- const STROKE_NAMES = Object.keys(STROKE_SIZES)
1792
-
1793
- // Text & notes expose the same size style as a label font size, under friendlier names.
1794
- const FONT_SIZES: Record<string, ScratchSize> = { regular: 'm', big: 'xl' }
1795
- const FONT_SIZE_NAMES = Object.keys(FONT_SIZES)
1796
-
1797
- // Rectangle fills — the UI toolbar's four options. Each user-facing name maps onto a
1798
- // tldraw DefaultFillStyle value (see ScratchFill for tldraw's semi/solid quirk). Keep
1799
- // in sync with FILL_OPTIONS in client/components/Scratchpad.tsx.
1800
- const FILL_STYLES: Record<string, ScratchFill> = {
1801
- none: 'none',
1802
- semi: 'solid',
1803
- pattern: 'pattern',
1804
- solid: 'fill'
1805
- }
1806
- const FILL_NAMES = Object.keys(FILL_STYLES)
1807
-
1808
- function hexToRgb(hex: string): [number, number, number] | null {
1809
- let h = hex.trim().replace(/^#/, '')
1810
- if (h.length === 3) h = h.replace(/(.)/g, '$1$1')
1811
- if (!/^[0-9a-fA-F]{6}$/.test(h)) return null
1812
- return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)]
1813
- }
1814
-
1815
- // Accept a palette name as-is, or snap any hex to the nearest palette color by
1816
- // squared RGB distance. Throws on anything else.
1817
- function parseColor(s: string): ScratchColor {
1818
- const lower = s.trim().toLowerCase()
1819
- if ((COLOR_NAMES as string[]).includes(lower)) return lower as ScratchColor
1820
- const rgb = hexToRgb(s)
1821
- if (!rgb) {
1822
- throw new Error(
1823
- `Unknown color "${s}". Use a hex like "#4465e9" or one of: ${COLOR_NAMES.join(', ')}.`
1824
- )
1825
- }
1826
- let best: ScratchColor = 'black'
1827
- let bestDist = Infinity
1828
- for (const name of COLOR_NAMES) {
1829
- const [r, g, b] = hexToRgb(COLOR_HEX[name])!
1830
- const d = (r - rgb[0]) ** 2 + (g - rgb[1]) ** 2 + (b - rgb[2]) ** 2
1831
- if (d < bestDist) {
1832
- bestDist = d
1833
- best = name
1834
- }
1835
- }
1836
- return best
1837
- }
1838
-
1839
- function parseStroke(s: string): ScratchSize {
1840
- const size = STROKE_SIZES[s.trim().toLowerCase()]
1841
- if (!size) throw new Error(`Unknown stroke "${s}". Use one of: ${STROKE_NAMES.join(', ')}.`)
1842
- return size
1843
- }
1844
-
1845
- function parseFontSize(s: string): ScratchSize {
1846
- const size = FONT_SIZES[s.trim().toLowerCase()]
1847
- if (!size) throw new Error(`Unknown font size "${s}". Use one of: ${FONT_SIZE_NAMES.join(', ')}.`)
1848
- return size
1849
- }
1850
-
1851
- function parseFill(s: string): ScratchFill {
1852
- const fill = FILL_STYLES[s.trim().toLowerCase()]
1853
- if (!fill) throw new Error(`Unknown fill "${s}". Use one of: ${FILL_NAMES.join(', ')}.`)
1854
- return fill
1855
- }
1856
-
1857
- // Resize preset for `add image` — defaults to 'lo' (keep the canvas light).
1858
- function parseImageQuality(s: string | undefined): ScratchImageQuality {
1859
- if (!s) return 'lo'
1860
- const q = s.trim().toLowerCase()
1861
- if (q === 'lo' || q === 'hi') return q
1862
- throw new Error(`Unknown quality "${s}". Use "lo" or "hi".`)
1863
- }
1864
-
1865
- // Optional styling shared across `add` commands — each command wires in only the
1866
- // controls its shape exposes (mirroring the UI's per-tool style bar).
1867
- const colorArg = {
1868
- type: 'string',
1869
- description: `Color: ${COLOR_NAMES.join(', ')}, or any hex (snapped to nearest)`
1870
- } as const
1871
- const strokeArg = {
1872
- type: 'string',
1873
- description: `Stroke weight: ${STROKE_NAMES.join(', ')}`
1874
- } as const
1875
- const fontSizeArg = {
1876
- type: 'string',
1877
- description: `Font size: ${FONT_SIZE_NAMES.join(', ')}`
1878
- } as const
1879
- const fillArg = {
1880
- type: 'string',
1881
- default: 'semi',
1882
- description: `Fill: ${FILL_NAMES.join(', ')} (default: semi)`
1883
- } as const
1884
-
1885
- // Build the optional style props from raw args. `stroke` and `fontSize` are two names
1886
- // for the same tldraw size style, so at most one is wired per command.
1887
- function styleArgs(args: {
1888
- color?: string
1889
- stroke?: string
1890
- fontSize?: string
1891
- fill?: string
1892
- }): ScratchStyle {
1893
- return {
1894
- ...(args.color ? { color: parseColor(args.color) } : {}),
1895
- ...(args.stroke ? { size: parseStroke(args.stroke) } : {}),
1896
- ...(args.fontSize ? { size: parseFontSize(args.fontSize) } : {}),
1897
- ...(args.fill ? { fill: parseFill(args.fill) } : {})
1898
- }
1899
- }
1900
-
1901
- type ScratchCliOp = ScratchOp | { kind: 'read' } | { kind: 'read-image'; name: string }
1902
-
1903
- // Round-trip one request through the control port and hand the reply to
1904
- // `onResult`. Mirrors the `bundle`/`theme` commands: one socket per invocation,
1905
- // print, exit. Shared by `scratch`, `call-server-fn`, and `debug logs`.
1906
- function sendControl(
1907
- path: string,
1908
- payload: Record<string, unknown>,
1909
- onResult: (res: Record<string, unknown>) => void | Promise<void>
1910
- ) {
1911
- const ws = new WebSocket(CONTROL_URL)
1912
- let connected = false
1913
- let responded = false
1914
- ws.onopen = () => {
1915
- connected = true
1916
- ws.send(JSON.stringify(payload))
1917
- }
1918
- ws.onmessage = async event => {
1919
- responded = true
1920
- const res = JSON.parse(String(event.data))
1921
- if (res.error) {
1922
- console.error('\n' + pc.red('✗') + ' ' + res.error + '\n')
1923
- ws.close()
1924
- process.exit(1)
1925
- }
1926
- await onResult(res)
1927
- // The stale-skill notice rides on stderr so it never corrupts a command's
1928
- // structured stdout (read's JSON, view's PNG path) while the agent still sees it.
1929
- const notice = await staleSkillNotice(path)
1930
- if (notice) console.error('\n' + pc.yellow(notice) + '\n')
1931
- ws.close()
1932
- process.exit(0)
1933
- }
1934
- ws.onclose = () => {
1935
- if (connected && !responded) {
1936
- console.error(
1937
- 'The server disconnected before acknowledging the command. Check the browser before retrying.'
1938
- )
1939
- process.exit(1)
1940
- }
1941
- }
1942
- ws.onerror = () => void exitControlUnreachable()
1943
- }
1944
-
1945
- function sendScratch(
1946
- path: string,
1947
- op: ScratchCliOp,
1948
- onResult: (res: Record<string, unknown>) => void | Promise<void>
1949
- ) {
1950
- sendControl(path, { type: 'scratch', path, op }, onResult)
1951
- }
1952
-
1953
- // Print the name a draw op landed on, so the agent can address it later.
1954
- function printAdded(res: Record<string, unknown>) {
1955
- const result = res.result as { name?: string } | undefined
1956
- console.log('\n' + pc.green('✓') + ' added ' + pc.bold(result?.name ?? '(shape)') + '\n')
1957
- }
1958
-
1959
- const dirArg = {
1960
- type: 'string',
1961
- default: '.',
1962
- description: 'Workspace directory (default: current)'
1963
- } as const
1964
-
1965
- const scratchRead = defineCommand({
1966
- meta: { name: 'read', description: 'Print the canvas shapes as JSON (served off disk)' },
1967
- args: { dir: dirArg },
1968
- run({ args }) {
1969
- sendScratch(resolve(args.dir), { kind: 'read' }, res => {
1970
- console.log(JSON.stringify(res.shapes ?? [], null, 2))
1971
- })
1972
- }
1973
- })
1974
-
1975
- const scratchView = defineCommand({
1976
- meta: { name: 'view', description: 'Render the canvas to a PNG (needs an open Scratchpad tab)' },
1977
- args: {
1978
- dir: dirArg,
1979
- out: { type: 'string', description: 'Output PNG path (default: a temp file)' }
1980
- },
1981
- async run({ args }) {
1982
- sendScratch(resolve(args.dir), { kind: 'view' }, async res => {
1983
- const result = res.result as { image?: string } | undefined
1984
- if (!result?.image) {
1985
- console.error(pc.red('No image returned'))
1986
- process.exit(1)
1987
- }
1988
- const b64 = result.image.replace(/^data:image\/png;base64,/, '')
1989
- const outPath = args.out ? resolve(args.out) : join(tmpdir(), `moi-scratch-${Date.now()}.png`)
1990
- await Bun.write(outPath, Buffer.from(b64, 'base64'))
1991
- console.log(outPath)
1992
- })
1993
- }
1994
- })
1995
-
1996
- // Image/video data URL mime → file extension, for naming the saved file. Kept in
1997
- // sync with the server's MIME_EXT (scratchpad-assets.ts) so avif/apng/video assets
1998
- // round-trip through `read-image` with a real extension instead of `.bin`.
1999
- const IMAGE_EXT: Record<string, string> = {
2000
- 'image/png': 'png',
2001
- 'image/jpeg': 'jpg',
2002
- 'image/jpg': 'jpg',
2003
- 'image/webp': 'webp',
2004
- 'image/gif': 'gif',
2005
- 'image/svg+xml': 'svg',
2006
- 'image/avif': 'avif',
2007
- 'image/apng': 'apng',
2008
- 'video/mp4': 'mp4',
2009
- 'video/webm': 'webm',
2010
- 'video/quicktime': 'mov'
2011
- }
2012
-
2013
- const scratchReadImage = defineCommand({
2014
- meta: {
2015
- name: 'read-image',
2016
- description: 'Save an image shape to a file by id (served off disk)'
2017
- },
2018
- args: {
2019
- id: { type: 'positional', required: true, description: 'Image shape id (from `scratch read`)' },
2020
- out: { type: 'string', description: 'Output file path (default: a temp file)' },
2021
- dir: dirArg
2022
- },
2023
- async run({ args }) {
2024
- sendScratch(resolve(args.dir), { kind: 'read-image', name: args.id }, async res => {
2025
- const src = res.src as string | undefined
2026
- if (!src) {
2027
- console.error(pc.red('No image data'))
2028
- process.exit(1)
2029
- }
2030
- // A remote (http) asset has no local bytes to write — just print the URL.
2031
- if (/^https?:\/\//.test(src)) {
2032
- console.log(src)
2033
- return
2034
- }
2035
- const m = src.match(/^data:([^;,]+)(;base64)?,(.*)$/s)
2036
- if (!m) {
2037
- console.error(pc.red('Unrecognized image source'))
2038
- process.exit(1)
2039
- }
2040
- const [, mime, base64, data] = m
2041
- const bytes = base64
2042
- ? Buffer.from(data, 'base64')
2043
- : Buffer.from(decodeURIComponent(data), 'utf8')
2044
- const ext = IMAGE_EXT[mime] ?? 'bin'
2045
- const safeId = args.id.replace(/[^a-zA-Z0-9_-]/g, '_')
2046
- const outPath = args.out
2047
- ? resolve(args.out)
2048
- : join(tmpdir(), `moi-scratch-${safeId}-${Date.now()}.${ext}`)
2049
- await Bun.write(outPath, bytes)
2050
- console.log(outPath)
2051
- })
2052
- }
2053
- })
2054
-
2055
- const scratchAddText = defineCommand({
2056
- meta: { name: 'text', description: 'Add a text shape' },
2057
- args: {
2058
- at: { type: 'string', required: true, description: 'Position "x,y"' },
2059
- text: { type: 'string', required: true, description: 'Text content' },
2060
- id: { type: 'string', description: 'Stable name to address this shape later' },
2061
- color: colorArg,
2062
- fontSize: fontSizeArg,
2063
- dir: dirArg
2064
- },
2065
- run({ args }) {
2066
- const { x, y } = parseXY(args.at)
2067
- sendScratch(
2068
- resolve(args.dir),
2069
- {
2070
- kind: 'add-text',
2071
- name: args.id ?? '',
2072
- x,
2073
- y,
2074
- text: args.text,
2075
- ...styleArgs({ color: args.color, fontSize: args.fontSize })
2076
- },
2077
- printAdded
2078
- )
2079
- }
2080
- })
2081
-
2082
- const scratchAddRect = defineCommand({
2083
- meta: { name: 'rect', description: 'Add a rectangle' },
2084
- args: {
2085
- at: { type: 'string', required: true, description: 'Top-left position "x,y"' },
2086
- size: { type: 'string', required: true, description: 'Size "w,h"' },
2087
- text: { type: 'string', description: 'Optional label' },
2088
- id: { type: 'string', description: 'Stable name to address this shape later' },
2089
- color: colorArg,
2090
- fill: fillArg,
2091
- fontSize: fontSizeArg,
2092
- dir: dirArg
2093
- },
2094
- run({ args }) {
2095
- const { x, y } = parseXY(args.at)
2096
- const { x: w, y: h } = parseXY(args.size)
2097
- sendScratch(
2098
- resolve(args.dir),
2099
- {
2100
- kind: 'add-rect',
2101
- name: args.id ?? '',
2102
- x,
2103
- y,
2104
- w,
2105
- h,
2106
- ...(args.text ? { text: args.text } : {}),
2107
- ...styleArgs({ color: args.color, fill: args.fill, fontSize: args.fontSize })
2108
- },
2109
- printAdded
2110
- )
2111
- }
2112
- })
2113
-
2114
- const scratchAddNote = defineCommand({
2115
- meta: { name: 'note', description: 'Add a sticky note' },
2116
- args: {
2117
- at: { type: 'string', required: true, description: 'Position "x,y"' },
2118
- text: { type: 'string', required: true, description: 'Note content' },
2119
- id: { type: 'string', description: 'Stable name to address this shape later' },
2120
- color: colorArg,
2121
- fontSize: fontSizeArg,
2122
- dir: dirArg
2123
- },
2124
- run({ args }) {
2125
- const { x, y } = parseXY(args.at)
2126
- sendScratch(
2127
- resolve(args.dir),
2128
- {
2129
- kind: 'add-note',
2130
- name: args.id ?? '',
2131
- x,
2132
- y,
2133
- text: args.text,
2134
- ...styleArgs({ color: args.color, fontSize: args.fontSize })
2135
- },
2136
- printAdded
2137
- )
2138
- }
2139
- })
2140
-
2141
- const scratchAddArrow = defineCommand({
2142
- meta: { name: 'arrow', description: 'Add an arrow connecting shapes or points' },
2143
- args: {
2144
- from: { type: 'string', required: true, description: 'Start: a shape name or "x,y"' },
2145
- to: { type: 'string', required: true, description: 'End: a shape name or "x,y"' },
2146
- id: { type: 'string', description: 'Stable name to address this shape later' },
2147
- elbow: {
2148
- type: 'boolean',
2149
- description: 'Right-angle (squared) routing for diagrams; default is a curved arc'
2150
- },
2151
- color: colorArg,
2152
- stroke: strokeArg,
2153
- dir: dirArg
2154
- },
2155
- run({ args }) {
2156
- sendScratch(
2157
- resolve(args.dir),
2158
- {
2159
- kind: 'add-arrow',
2160
- name: args.id ?? '',
2161
- from: parseEnd(args.from),
2162
- to: parseEnd(args.to),
2163
- ...(args.elbow ? { elbow: true } : {}),
2164
- ...styleArgs({ color: args.color, stroke: args.stroke })
2165
- },
2166
- printAdded
2167
- )
2168
- }
2169
- })
2170
-
2171
- const scratchAddImage = defineCommand({
2172
- meta: { name: 'image', description: 'Add an image from a file (resized to fit the canvas)' },
2173
- args: {
2174
- path: {
2175
- type: 'positional',
2176
- required: true,
2177
- description: 'Path to an image file (png/jpg/webp/gif)'
2178
- },
2179
- at: { type: 'string', description: 'Top-left position "x,y" (default: 0,0)' },
2180
- id: { type: 'string', description: 'Stable name to address this shape later' },
2181
- quality: { type: 'string', description: 'Resize: lo (default, smaller) or hi (sharper)' },
2182
- dir: dirArg
2183
- },
2184
- run({ args }) {
2185
- const { x, y } = args.at ? parseXY(args.at) : { x: 0, y: 0 }
2186
- sendScratch(
2187
- resolve(args.dir),
2188
- {
2189
- kind: 'add-image',
2190
- name: args.id ?? '',
2191
- x,
2192
- y,
2193
- path: resolve(args.path),
2194
- quality: parseImageQuality(args.quality)
2195
- },
2196
- printAdded
2197
- )
2198
- }
2199
- })
2200
-
2201
- const scratchAdd = defineCommand({
2202
- meta: { name: 'add', description: 'Add a shape: text, rect, note, arrow, or image' },
2203
- subCommands: {
2204
- text: scratchAddText,
2205
- rect: scratchAddRect,
2206
- note: scratchAddNote,
2207
- arrow: scratchAddArrow,
2208
- image: scratchAddImage
2209
- }
2210
- })
2211
-
2212
- const scratchMove = defineCommand({
2213
- meta: { name: 'move', description: 'Move a shape to a new position' },
2214
- args: {
2215
- id: { type: 'positional', required: true, description: 'Shape name' },
2216
- to: { type: 'string', required: true, description: 'New position "x,y"' },
2217
- dir: dirArg
2218
- },
2219
- run({ args }) {
2220
- const { x, y } = parseXY(args.to)
2221
- sendScratch(resolve(args.dir), { kind: 'move', name: args.id, x, y }, () =>
2222
- console.log('\n' + pc.green('✓') + ' moved ' + pc.bold(args.id) + '\n')
2223
- )
2224
- }
2225
- })
2226
-
2227
- const scratchSet = defineCommand({
2228
- meta: { name: 'set', description: "Relabel / edit a shape's text" },
2229
- args: {
2230
- id: { type: 'positional', required: true, description: 'Shape name' },
2231
- text: { type: 'string', required: true, description: 'New text' },
2232
- dir: dirArg
2233
- },
2234
- run({ args }) {
2235
- sendScratch(resolve(args.dir), { kind: 'set', name: args.id, text: args.text }, () =>
2236
- console.log('\n' + pc.green('✓') + ' updated ' + pc.bold(args.id) + '\n')
2237
- )
2238
- }
2239
- })
2240
-
2241
- const scratchDelete = defineCommand({
2242
- meta: { name: 'delete', description: 'Delete a shape' },
2243
- args: {
2244
- id: { type: 'positional', required: true, description: 'Shape name' },
2245
- dir: dirArg
2246
- },
2247
- run({ args }) {
2248
- sendScratch(resolve(args.dir), { kind: 'delete', name: args.id }, () =>
2249
- console.log('\n' + pc.green('✓') + ' deleted ' + pc.bold(args.id) + '\n')
2250
- )
2251
- }
2252
- })
2253
-
2254
- const scratchClear = defineCommand({
2255
- meta: { name: 'clear', description: 'Delete every shape — wipe the whole canvas' },
2256
- args: { dir: dirArg },
2257
- run({ args }) {
2258
- sendScratch(resolve(args.dir), { kind: 'clear' }, () =>
2259
- console.log('\n' + pc.green('✓') + ' cleared the canvas\n')
2260
- )
2261
- }
2262
- })
2263
-
2264
- const scratch = defineCommand({
2265
- meta: {
2266
- name: 'scratch',
2267
- description: 'Read and draw on the workspace Scratchpad canvas'
2268
- },
2269
- subCommands: {
2270
- read: scratchRead,
2271
- 'read-image': scratchReadImage,
2272
- view: scratchView,
2273
- add: scratchAdd,
2274
- move: scratchMove,
2275
- set: scratchSet,
2276
- delete: scratchDelete,
2277
- clear: scratchClear
2278
- }
2279
- })
2280
-
2281
- // ---- self-correction commands (docs/self-correction.md) ---------------------
2282
-
2283
- const callServerFn = defineCommand({
2284
- meta: {
2285
- name: 'call-server-fn',
2286
- description: 'Invoke an applet .server.ts function in an isolated one-shot worker (smoke test)'
2287
- },
2288
- args: {
2289
- fn: {
2290
- type: 'positional',
2291
- required: true,
2292
- description: 'Function path: <module>/<fn>, e.g. widgets/hello/getGreeting'
2293
- },
2294
- args: {
2295
- type: 'positional',
2296
- required: false,
2297
- description: 'Arguments as one JSON array, e.g. \'["ann", 10]\' (default [])'
2298
- },
2299
- dir: dirArg
2300
- },
2301
- run({ args }) {
2302
- const path = resolve(args.dir)
2303
- sendControl(
2304
- path,
2305
- { type: 'call-server-fn', path, fn: args.fn, args: args.args ?? '[]' },
2306
- res => {
2307
- // The worker replies devalue-encoded (same wire format the browser RPC
2308
- // parses), so Map/Set/Date render readably through Bun.inspect.
2309
- const value = devalueParse(String(res.result))
2310
- console.log(Bun.inspect(value, { depth: 8, colors: process.stdout.isTTY }))
2311
- // Duration on stderr: stdout stays clean data, and a slow call is a
2312
- // warning sign worth surfacing (browser RPC times out at 30s).
2313
- console.error(pc.dim(`↩ ${res.ms}ms`))
2314
- }
2315
- )
2316
- }
2317
- })
2318
-
2319
- // Compact relative age for a journal row: "just now", "4m ago", "2h ago", …
2320
- function agoLabel(ts: number): string {
2321
- const s = Math.max(0, Math.round((Date.now() - ts) / 1000))
2322
- if (s < 60) return 'just now'
2323
- if (s < 3600) return `${Math.round(s / 60)}m ago`
2324
- if (s < 86400) return `${Math.round(s / 3600)}h ago`
2325
- return `${Math.round(s / 86400)}d ago`
2326
- }
2327
-
2328
- // Where a journal entry points: the server function for rpc rows, else the applet.
2329
- function logSubject(e: {
2330
- source: string
2331
- kind?: string
2332
- name?: string
2333
- module?: string
2334
- fn?: string
2335
- }): string {
2336
- if (e.module) return `${e.module}/${e.fn ?? '?'}`
2337
- if (e.name) return `${e.kind ?? 'applet'} ${e.name}`
2338
- return 'unattributed'
2339
- }
2340
-
2341
- const MAX_LOG_MESSAGE_LINES = 12
2342
-
2343
- const debugLogs = defineCommand({
2344
- meta: {
2345
- name: 'logs',
2346
- description: 'Applet runtime errors on record (load / render / rpc / build failures)'
2347
- },
2348
- args: {
2349
- dir: dirArg,
2350
- only: appletOnlyArg,
2351
- json: {
2352
- type: 'boolean',
2353
- default: false,
2354
- description: 'Machine-readable output, includes stacks and epoch timestamps'
2355
- },
2356
- clear: { type: 'boolean', default: false, description: 'Wipe the journal' }
2357
- },
2358
- run({ args }) {
2359
- const only = readAppletSelector(args.only)
2360
- const path = resolve(args.dir)
2361
- if (args.clear) {
2362
- if (only) {
2363
- console.error('\n' + pc.red('✗') + ' Cannot combine --only with --clear.\n')
2364
- process.exit(1)
2365
- }
2366
- sendControl(path, { type: 'debug:logs', path, clear: true }, res => {
2367
- console.log('\n' + pc.green('✓') + ` cleared ${res.cleared ?? 0} entries\n`)
2368
- })
2369
- return
2370
- }
2371
- sendControl(path, { type: 'debug:logs', path }, res => {
2372
- let entries = (Array.isArray(res.entries) ? res.entries : []) as AppletLogEntry[]
2373
- if (only) {
2374
- entries = entries.filter(
2375
- entry =>
2376
- entry.kind &&
2377
- entry.name &&
2378
- appletSelectorMatches(only, entry.kind === 'widget' ? 'widgets' : 'views', entry.name)
2379
- )
2380
- }
2381
- if (args.json) {
2382
- console.log(JSON.stringify(entries, null, 2))
2383
- return
2384
- }
2385
- if (entries.length === 0) {
2386
- const suffix = only ? ` for ${only}` : ''
2387
- console.log(
2388
- '\n' + pc.bold('moi debug logs') + pc.dim(` — no applet errors on record${suffix}`) + '\n'
2389
- )
2390
- return
2391
- }
2392
- const suffix = only ? ` for ${only}` : ''
2393
- console.log(
2394
- '\n' +
2395
- pc.bold('moi debug logs') +
2396
- pc.dim(` — ${entries.length} error(s) on record${suffix}`) +
2397
- '\n'
2398
- )
2399
- for (const e of entries) {
2400
- const count = e.count > 1 ? pc.dim(` ×${e.count}`) : ''
2401
- console.log(
2402
- ` ${pc.dim(agoLabel(e.ts).padEnd(10))} ${e.source.padEnd(7)} ${pc.bold(logSubject(e))}${count}`
2403
- )
2404
- const lines = e.message.split('\n')
2405
- for (const line of lines.slice(0, MAX_LOG_MESSAGE_LINES)) {
2406
- console.log(' ' + line)
2407
- }
2408
- if (lines.length > MAX_LOG_MESSAGE_LINES) {
2409
- console.log(pc.dim(` … ${lines.length - MAX_LOG_MESSAGE_LINES} more lines (--json)`))
2410
- }
2411
- console.log()
2412
- }
2413
- console.log(
2414
- pc.dim(' Entries clear when their applet next builds successfully, or via --clear.') + '\n'
2415
- )
2416
- })
2417
- }
2418
- })
2419
-
2420
- // Experimental workspace-debugging toolbox. One subcommand for now (`logs`);
2421
- // more introspection (worker state, RPC traces, …) may hang off it later.
2422
- const debug = defineCommand({
2423
- meta: {
2424
- name: 'debug',
2425
- description: 'Debug the workspace (experimental) — `moi debug logs` for applet errors'
2426
- },
2427
- subCommands: { logs: debugLogs }
2428
- })
2429
-
2430
- // ---- workspace tabs ----------------------------------------------------------
2431
-
2432
- // The listing behind `moi tabs`: every tab (static + views), one per row, the
2433
- // saved default (`layout.tabs.active`) marked. The
2434
- // addresses are documented in docs/navigation.md.
2435
- function runTabsList(dir: string) {
2436
- const path = resolve(dir)
2437
- sendControl(path, { type: 'tabs', path }, res => {
2438
- type Row = { title: string; isDefault: boolean; href?: string }
2439
- const rows: Row[] = Array.isArray(res.tabs) ? (res.tabs as Row[]) : []
2440
- console.log(
2441
- '\n' + pc.bold('moi tabs') + pc.dim(' — workspace tabs, the default one marked') + '\n'
2442
- )
2443
- console.log(
2444
- columns(
2445
- ['', 'title', 'address'].map(h => pc.dim(h)),
2446
- rows.map(row => [
2447
- row.isDefault ? pc.green('●') : ' ',
2448
- row.isDefault ? pc.bold(row.title) : row.title,
2449
- row.href ?? '—'
2450
- ])
2451
- )
2452
- )
2453
- console.log('\n' + pc.dim(' Open one: moi navigate <address>') + '\n')
2454
- })
2455
- }
2456
-
2457
- const navigate = defineCommand({
2458
- meta: {
2459
- name: 'navigate',
2460
- description: 'Navigate the last active browser showing this workspace'
2461
- },
2462
- args: {
2463
- href: {
2464
- type: 'positional',
2465
- required: true,
2466
- description: 'Workspace address, e.g. moi:/views/events?eventId=123'
2467
- },
2468
- dir: dirArg
2469
- },
2470
- run({ args }) {
2471
- try {
2472
- parseMoiHref(args.href)
2473
- } catch (error) {
2474
- console.error(error instanceof Error ? error.message : 'Invalid workspace address')
2475
- process.exit(1)
2476
- }
2477
- const path = resolve(args.dir)
2478
- sendControl(path, { type: 'navigate', path, href: args.href }, res => {
2479
- console.log('\n' + pc.green('✓') + ' Navigated to ' + pc.bold(String(res.href)) + '\n')
2480
- })
2481
- }
2482
- })
2483
-
2484
- const tabs = defineCommand({
2485
- meta: { name: 'tabs', description: 'List workspace tabs and their navigation addresses' },
2486
- args: { dir: dirArg },
2487
- run({ args }) {
2488
- if (args._.length) {
2489
- console.error('moi tabs only lists tabs. Use moi navigate <address> to navigate.')
2490
- process.exit(1)
2491
- }
2492
- runTabsList(args.dir)
2493
- }
2494
- })
2495
-
2496
- // Re-copy bundled skills into a workspace, then report what changed. Pure
2497
- // filesystem op — no running server needed. Resolves the workspace root the
2498
- // same way `moi bundle` does, so it works from `.moi/` or any subdirectory.
2499
- async function runSkillUpdate(cwd: string): Promise<void> {
2500
- // Type-aware: an OpenClaw workspace keeps its skills in `skills/`, so the
2501
- // update must target the same dir the agent actually loads from.
2502
- const { root, type } = await resolveWorkspace(cwd)
2503
- const { before, status, changedSkills, updatedAppletTypes } = await updateWorkspaceSkills(
2504
- root,
2505
- type ?? 'claude-code'
2506
- )
2507
- const after = status.skills
2508
- const heading = changedSkills.length > 0 ? 'Skills updated in ' : 'Skills unchanged in '
2509
-
2510
- console.log('\n' + pc.green('✓') + ' ' + heading + pc.bold(root) + '\n')
2511
- printSkillUpdateTable(before, after, changedSkills)
2512
- for (const file of updatedAppletTypes) {
2513
- console.log(pc.dim(' Applet types regenerated: ') + pc.bold(`.moi/${file}\n`))
2514
- }
2515
- }
2516
-
2517
- function printSkillUpdateTable(
2518
- before: WorkspaceSkillStatus[],
2519
- after: WorkspaceSkillStatus[],
2520
- changedSkills: string[]
2521
- ): void {
2522
- const changedSkillNames = new Set(changedSkills)
2523
- console.log(
2524
- columns(
2525
- ['skill', 'from', 'to'].map(h => pc.dim(h)),
2526
- after.map(s => {
2527
- const prev = before.find(b => b.name === s.name)?.installed ?? null
2528
- const versionChanged = prev !== s.installed
2529
- const filesChanged = changedSkillNames.has(s.name)
2530
- return [
2531
- s.name,
2532
- prev ?? pc.dim('none'),
2533
- versionChanged
2534
- ? pc.green(s.installed ?? '?')
2535
- : filesChanged
2536
- ? pc.green((s.installed ?? '?') + ' (files changed)')
2537
- : pc.dim((s.installed ?? '?') + ' (no change)')
2538
- ]
2539
- })
2540
- )
2541
- )
2542
- const nextStep =
2543
- changedSkills.length > 0
2544
- ? ` Reload changed skills before using them again: ${changedSkills.join(', ')}.`
2545
- : ' No skill files changed. Keep using the copies already in context.'
2546
- console.log('\n' + pc.dim(nextStep) + '\n')
2547
- }
2548
-
2549
- // Colored status label for one skill row: minor+ behind is actionable, a patch
2550
- // gap is informational, otherwise current.
2551
- function skillState(s: WorkspaceSkillStatus): string {
2552
- if (isMinorBehind(s.installed, s.bundled)) return pc.yellow('update available')
2553
- if (isBehind(s.installed, s.bundled)) return pc.dim('patch behind')
2554
- return pc.green('up to date')
2555
- }
2556
-
2557
- // `update` and `install` are the same operation under two names (install kept
2558
- // for symmetry with how skills first land in a workspace). `dir` is a `--dir`
2559
- // option, not a positional: citty treats a bare positional on a command that
2560
- // carries subcommands as an unknown subcommand. Reuses the shared `dirArg`.
2561
- const defineSkillUpdate = (name: string, description: string) =>
2562
- defineCommand({
2563
- meta: { name, description },
2564
- args: { dir: dirArg },
2565
- async run({ args }) {
2566
- await runSkillUpdate(resolve(args.dir))
2567
- }
2568
- })
2569
-
2570
- const skillSubCommands = {
2571
- update: defineSkillUpdate(
2572
- 'update',
2573
- 'Update this workspace’s skills to the version shipped with the CLI'
2574
- ),
2575
- install: defineSkillUpdate('install', 'Alias for `moi skill update`')
2576
- }
2577
-
2578
- const skill = defineCommand({
2579
- meta: { name: 'skill', description: 'Show or update the workspace skills shipped with moi' },
2580
- subCommands: skillSubCommands,
2581
- args: { dir: dirArg },
2582
- async run({ args, rawArgs }) {
2583
- // citty runs this parent handler even after dispatching a subcommand, so
2584
- // bail when one was given — otherwise `moi skill update` also prints status.
2585
- const sub = rawArgs.find(a => !a.startsWith('-'))
2586
- if (sub && sub in skillSubCommands) return
2587
-
2588
- const { root, type } = await resolveWorkspace(resolve(args.dir))
2589
- const statuses = await skillStatuses(root, type)
2590
-
2591
- console.log('\n' + pc.bold('moi skill') + pc.dim(' — workspace skills') + '\n')
2592
- console.log(
2593
- columns(
2594
- ['skill', 'installed', 'bundled', 'status'].map(h => pc.dim(h)),
2595
- statuses.map(s => [
2596
- s.name,
2597
- s.installed ?? pc.dim('—'),
2598
- s.bundled ?? pc.dim('—'),
2599
- skillState(s)
2600
- ])
2601
- )
2602
- )
2603
- if (statuses.some(s => isBehind(s.installed, s.bundled))) {
2604
- console.log('\n' + pc.dim(' Run ') + pc.bold('moi skill update') + pc.dim(' to refresh.'))
2605
- }
2606
- console.log()
2607
- }
2608
- })
2609
-
2610
- // ---- service ----------------------------------------------------------------
2611
-
2612
- function serviceFail(err: unknown): never {
2613
- const message = err instanceof ServiceError ? err.message : String(err)
2614
- console.error('\n' + pc.red('✗') + ' ' + message + '\n')
2615
- process.exit(1)
2616
- }
2617
-
2618
- // Shared success line after install/restart: did the server actually come up,
2619
- // and on which version?
2620
- function printServiceServer(info: Awaited<ReturnType<typeof queryServerInfo>>) {
2621
- if (info) {
2622
- console.log(
2623
- ' server ' +
2624
- pc.bold(`v${info.version}`) +
2625
- ` running on http://localhost:${info.port}` +
2626
- pc.dim(` (pid ${info.pid})`)
2627
- )
2628
- const mismatch = versionMismatchNotice(info.version)
2629
- if (mismatch) console.log('\n' + mismatch)
2630
- } else {
2631
- console.log(
2632
- ' ' +
2633
- pc.yellow('server did not come up — check `moi service logs`') +
2634
- pc.dim(' (it may still be starting)')
2635
- )
2636
- }
2637
- }
2638
-
2639
- const serviceInstall = defineCommand({
2640
- meta: {
2641
- name: 'install',
2642
- description: 'Install and start the user service (launchd on macOS, systemd on Linux)'
2643
- },
2644
- args: {
2645
- port: { type: 'string', description: 'HTTP port for the service server (default: 13337)' },
2646
- env: {
2647
- type: 'string',
2648
- description:
2649
- 'Extra env var names to capture from this shell, comma-separated (e.g. --env MY_TOKEN,OTHER)'
2650
- }
2651
- },
2652
- async run({ args }) {
2653
- // Check the install shape first: telling someone to stop their server only
2654
- // to then refuse the checkout would be a pointless round-trip.
2655
- const analysis = analyzeInstall()
2656
- if (analysis.kind !== 'global') {
2657
- try {
2658
- await installService() // throws the precise refusal for this analysis
2659
- } catch (err) {
2660
- serviceFail(err)
2661
- }
2662
- }
2663
- const port = args.port ? Number(args.port) : undefined
2664
- if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535)) {
2665
- serviceFail(new ServiceError(`Invalid --port value "${args.port}" — use a port number.`))
2666
- }
2667
- // citty hands back an array when the flag repeats — accept both shapes.
2668
- const envArg = Array.isArray(args.env) ? args.env.join(',') : args.env
2669
- const extraEnv = (envArg ?? '')
2670
- .split(',')
2671
- .map(k => k.trim())
2672
- .filter(Boolean)
2673
- const serviceEnv = captureServiceEnv(process.env, dirname(process.execPath), extraEnv)
2674
- const missingEnv = extraEnv.filter(key => !(key in serviceEnv))
2675
- if (missingEnv.length > 0) {
2676
- serviceFail(
2677
- new ServiceError(
2678
- `--env ${missingEnv.join(', ')}: not set in this shell (or the value is not capturable).`
2679
- )
2680
- )
2681
- }
2682
- // A foreground `moi start` holds the same ports the service needs. Refuse
2683
- // rather than install a unit that instantly fails on bind.
2684
- const runningInfo = await queryServerInfo()
2685
- const foreground = (await isServerRunning()) && !runningInfo?.service
2686
- if (foreground) {
2687
- serviceFail(
2688
- new ServiceError(
2689
- 'A foreground server is running' +
2690
- (runningInfo?.pid ? ` (pid ${runningInfo.pid})` : '') +
2691
- '.\n Stop it (Ctrl-C in its terminal), then rerun `moi service install`.'
2692
- )
2693
- )
2694
- }
2695
- try {
2696
- const result = await installService({ port, extraEnv })
2697
- console.log(
2698
- '\n' +
2699
- pc.green('✓') +
2700
- ' Service installed ' +
2701
- pc.dim(`(${process.platform === 'darwin' ? 'launchd' : 'systemd user unit'})`)
2702
- )
2703
- console.log(' unit ' + pc.dim(tildifyPath(result.unitPath)))
2704
- if (result.logPath) console.log(' logs ' + pc.dim(tildifyPath(result.logPath)))
2705
- printServiceServer(result.info)
2706
- console.log(pc.dim('\n Starts on login, restarts on crash, survives reboots.'))
2707
- for (const note of result.notes) console.log(pc.yellow(' ' + note))
2708
- console.log()
2709
- } catch (err) {
2710
- serviceFail(err)
2711
- }
2712
- }
2713
- })
2714
-
2715
- const serviceUninstall = defineCommand({
2716
- meta: { name: 'uninstall', description: 'Stop the service and remove its unit' },
2717
- async run() {
2718
- try {
2719
- const { unitPath, existed } = await uninstallService()
2720
- if (!existed) {
2721
- console.log(
2722
- '\n' +
2723
- pc.dim('○') +
2724
- ' Service is not installed ' +
2725
- pc.dim(`(${tildifyPath(unitPath)})`) +
2726
- '\n'
2727
- )
2728
- return
2729
- }
2730
- console.log(
2731
- '\n' + pc.green('✓') + ' Service removed ' + pc.dim(`(${tildifyPath(unitPath)})`) + '\n'
2732
- )
2733
- } catch (err) {
2734
- serviceFail(err)
2735
- }
2736
- }
2737
- })
2738
-
2739
- const serviceRestart = defineCommand({
2740
- meta: { name: 'restart', description: 'Restart the service server' },
2741
- async run() {
2742
- try {
2743
- const info = await restartService()
2744
- console.log('\n' + pc.green('✓') + ' Service restarted')
2745
- printServiceServer(info)
2746
- console.log()
2747
- } catch (err) {
2748
- serviceFail(err)
2749
- }
2750
- }
2751
- })
2752
-
2753
- const serviceLogs = defineCommand({
2754
- meta: { name: 'logs', description: 'Show server logs (journalctl on Linux, log file on macOS)' },
2755
- args: {
2756
- lines: { type: 'string', default: '80', description: 'How many trailing lines to show' },
2757
- follow: {
2758
- type: 'boolean',
2759
- alias: 'f',
2760
- default: false,
2761
- description: 'Keep following new output'
2762
- }
2763
- },
2764
- async run({ args }) {
2765
- const n = Math.max(1, Number(args.lines) || 80)
2766
- if (process.platform === 'linux') {
2767
- // journald owns the log (bounded, rotated). Inherit stdio so -f streams.
2768
- const argv = ['journalctl', '--user', '-u', 'moi.service', '-n', String(n), '--no-pager']
2769
- if (args.follow) argv.push('-f')
2770
- const proc = Bun.spawn(argv, { stdin: 'inherit', stdout: 'inherit', stderr: 'inherit' })
2771
- process.exit(await proc.exited)
2772
- }
2773
- const logPath = serviceLogPath()
2774
- if (!existsSync(logPath)) {
2775
- console.log('\n' + pc.dim('○') + ' No logs yet ' + pc.dim(`(${tildifyPath(logPath)})`) + '\n')
2776
- process.exit(0)
2777
- }
2778
- console.error(pc.dim(tildifyPath(logPath)))
2779
- const proc = Bun.spawn(['tail', '-n', String(n), ...(args.follow ? ['-F'] : []), logPath], {
2780
- stdin: 'inherit',
2781
- stdout: 'inherit',
2782
- stderr: 'inherit'
2783
- })
2784
- process.exit(await proc.exited)
2785
- }
2786
- })
2787
-
2788
- function tildifyPath(p: string): string {
2789
- const home = process.env.HOME
2790
- return home && p.startsWith(home) ? '~' + p.slice(home.length) : p
2791
- }
2792
-
2793
- async function runServiceStatus() {
2794
- try {
2795
- const s = await serviceStatus()
2796
- const flavor = s.platform === 'darwin' ? 'launchd user agent' : 'systemd user unit'
2797
- console.log('\n' + pc.bold('moi service') + pc.dim(` — ${flavor}`))
2798
- console.log()
2799
- if (!s.installed) {
2800
- console.log(' ' + pc.dim('○') + ' Not installed')
2801
- console.log(
2802
- pc.dim(' Run `moi service install` to start moi on login and keep it running.')
2803
- )
2804
- console.log()
2805
- process.exit(0)
2806
- }
2807
- const rt = s.runtime
2808
- const stateLabel =
2809
- rt === null
2810
- ? pc.dim('unknown')
2811
- : rt.state === 'running'
2812
- ? pc.green('● running') + (rt.pid ? pc.dim(` (pid ${rt.pid})`) : '')
2813
- : rt.state === 'failed'
2814
- ? pc.red('✗ failed') + pc.dim(rt.detail ? ` (${rt.detail})` : '')
2815
- : rt.state === 'unavailable'
2816
- ? pc.yellow('? unavailable') + pc.dim(rt.detail ? ` — ${rt.detail}` : '')
2817
- : pc.dim('○ ' + rt.state)
2818
- console.log(' state ' + stateLabel)
2819
- console.log(' unit ' + pc.dim(tildifyPath(s.unitPath)))
2820
- if (s.logPath)
2821
- console.log(' logs ' + pc.dim(tildifyPath(s.logPath)) + pc.dim(' (`moi service logs`)'))
2822
- else
2823
- console.log(' logs ' + pc.dim('journalctl --user -u moi.service (`moi service logs`)'))
2824
- const info = await queryServerInfo()
2825
- if (info) {
2826
- console.log(
2827
- ' server ' +
2828
- pc.bold(`v${info.version}`) +
2829
- pc.dim(` on http://localhost:${info.port} (pid ${info.pid})`)
2830
- )
2831
- if (!info.service) {
2832
- console.log(
2833
- pc.yellow(' ⚠ The running server is a foreground `moi start`, not the service.')
2834
- )
2835
- }
2836
- } else if (rt?.state === 'running') {
2837
- console.log(' server ' + pc.yellow('unreachable on the control port'))
2838
- }
2839
- console.log()
2840
- if (s.binMissing && s.bin) {
2841
- console.log(
2842
- pc.yellow(` ⚠ The service execs ${s.bin}, which no longer exists`) +
2843
- pc.dim(' (moi moved or was reinstalled elsewhere).') +
2844
- '\n' +
2845
- pc.dim(' Rerun `moi service install` to re-capture paths.')
2846
- )
2847
- }
2848
- if (s.bunMissing) {
2849
- console.log(
2850
- pc.yellow(' ⚠ No bun on the service PATH — the server cannot start.') +
2851
- '\n' +
2852
- pc.dim(' Reinstall bun, then rerun `moi service install`.')
2853
- )
2854
- }
2855
- if (s.linger === 'disabled') {
2856
- console.log(
2857
- pc.yellow(' ⚠ Lingering is off — the service stops when your last session ends.') +
2858
- '\n' +
2859
- pc.dim(' Enable: loginctl enable-linger')
2860
- )
2861
- }
2862
- const mismatch = info ? versionMismatchNotice(info.version) : null
2863
- if (mismatch) console.log(mismatch.replace(/^/gm, ' ').replace(/^ {2}⚠/, ' ⚠') + '\n')
2864
- process.exit(0)
2865
- } catch (err) {
2866
- serviceFail(err)
2867
- }
2868
- }
2869
-
2870
- const serviceSubCommands = {
2871
- install: serviceInstall,
2872
- uninstall: serviceUninstall,
2873
- restart: serviceRestart,
2874
- logs: serviceLogs
2875
- }
2876
-
2877
- const service = defineCommand({
2878
- meta: {
2879
- name: 'service',
2880
- description: 'Run moi as a user service: `moi service install|uninstall|restart|logs`'
2881
- },
2882
- subCommands: serviceSubCommands,
2883
- async run({ rawArgs }) {
2884
- // citty invokes the parent run even after dispatching a subcommand — only
2885
- // show status when none ran (same pattern as `moi env` / `moi tabs`).
2886
- const sub = rawArgs.find(a => !a.startsWith('-'))
2887
- if (sub && Object.hasOwn(serviceSubCommands, sub)) return
2888
- await runServiceStatus()
2889
- }
2890
- })
2891
-
2892
- // ---- update -----------------------------------------------------------------
2893
-
2894
- const update = defineCommand({
2895
- meta: {
2896
- name: 'update',
2897
- description: 'Update moi to the latest published version'
2898
- },
2899
- args: {
2900
- check: {
2901
- type: 'boolean',
2902
- default: false,
2903
- description:
2904
- 'Only check the registry, change nothing. Exit 0: up to date (or nothing to update), 1: update available, 2: check failed.'
2905
- }
2906
- },
2907
- async run({ args }) {
2908
- // A checkout has no owning package manager — updating means `git pull`.
2909
- const analysis = analyzeInstall()
2910
- if (analysis.kind === 'checkout') {
2911
- console.log(
2912
- '\n' +
2913
- pc.yellow('◆') +
2914
- ` This moi runs from a source tree (${analysis.reason}) — update it with git instead.\n`
2915
- )
2916
- process.exit(0)
2917
- }
2918
-
2919
- console.log('\n' + pc.bold('moi update') + pc.dim(` — installed v${VERSION}`))
2920
-
2921
- if (isPrerelease(VERSION)) {
2922
- console.log(
2923
- '\n' +
2924
- pc.yellow('◆') +
2925
- ' Prerelease installs are updated manually — pick the tag you want:\n' +
2926
- pc.dim(' bun i -g moi-computer@next (or @latest to leave the prerelease)\n')
2927
- )
2928
- process.exit(0)
2929
- }
2930
-
2931
- let latest: string
2932
- try {
2933
- latest = await fetchLatestVersion()
2934
- } catch (err) {
2935
- console.error(
2936
- '\n' + pc.red('✗') + ' ' + (err instanceof Error ? err.message : String(err)) + '\n'
2937
- )
2938
- // Under --check, exit 2 keeps "check failed" distinct from "update
2939
- // available" (exit 1) for scripts and agents.
2940
- process.exit(args.check ? 2 : 1)
2941
- }
2942
-
2943
- if (!isNewer(latest, VERSION)) {
2944
- console.log(pc.green('✓') + ` Already up to date (latest is v${latest})`)
2945
- // --check is side-effect-free: skip the server sync, which can restart
2946
- // a lagging service. `moi status` reports that lag without acting on it.
2947
- if (!args.check) await reportServerFreshness()
2948
- process.exit(0)
2949
- }
2950
-
2951
- if (args.check) {
2952
- console.log(
2953
- ` update available: ${pc.bold('v' + latest)}` + pc.dim(' — run `moi update` to install\n')
2954
- )
2955
- process.exit(1)
2956
- }
2957
-
2958
- console.log(` latest is ${pc.bold('v' + latest)} — updating`)
2959
-
2960
- const pm = await detectPackageManager()
2961
- if (!pm) {
2962
- console.error(
2963
- '\n' +
2964
- pc.red('✗') +
2965
- ' Could not tell which package manager owns this install' +
2966
- pc.dim(` (${analysis.root})`) +
2967
- '.\n Update it yourself with the one you installed moi with:\n' +
2968
- manualUpdateLines(latest)
2969
- .map(l => pc.dim(' ' + l))
2970
- .join('\n') +
2971
- '\n'
2972
- )
2973
- process.exit(1)
2974
- }
2975
-
2976
- const argv = updateArgv(pm, latest)
2977
- console.log(pc.dim(` via ${pm}: ${argv.join(' ')}\n`))
2978
- const code = await runPackageManager(argv)
2979
- if (code !== 0) {
2980
- console.error('\n' + pc.red('✗') + ` ${pm} exited with code ${code}.`)
2981
- console.error(pc.dim(' Run it manually: ') + argv.join(' '))
2982
- if (pm === 'npm') {
2983
- console.error(
2984
- pc.dim(
2985
- ' If it failed with EACCES, your npm prefix is root-owned — fix ownership or use a user-level prefix.'
2986
- )
2987
- )
2988
- }
2989
- console.error()
2990
- process.exit(1)
2991
- }
2992
-
2993
- // Trust but verify: ask the bin users actually run what version it is now.
2994
- // A stale answer means the update landed somewhere PATH does not point.
2995
- const binVersion = analysis.kind === 'global' ? await installedBinVersion(analysis.bin) : null
2996
- if (binVersion === latest) {
2997
- console.log('\n' + pc.green('✓') + ` moi updated to ${pc.bold('v' + latest)}`)
2998
- } else if (binVersion) {
2999
- console.log(
3000
- '\n' +
3001
- pc.yellow('⚠') +
3002
- ` ${pm} finished, but \`moi\` on PATH reports v${binVersion} (expected v${latest}).` +
3003
- '\n' +
3004
- pc.dim(' Another install may shadow the updated one — check `which moi`.')
3005
- )
3006
- } else {
3007
- console.log('\n' + pc.green('✓') + ` ${pm} finished (v${latest})`)
3008
- }
3009
-
3010
- await reportServerFreshness(latest)
3011
- console.log()
3012
- process.exit(0)
3013
- }
3014
- })
3015
-
3016
- // After an update (or an up-to-date check), bring the running server along:
3017
- // restart a service-managed one and verify the version it comes back with; a
3018
- // foreground server in someone's terminal only ever gets a warning.
3019
- async function reportServerFreshness(expected?: string) {
3020
- const running = await isServerRunning()
3021
- if (!running) return
3022
- const info = await queryServerInfo()
3023
- if (!info) {
3024
- console.log(
3025
- pc.yellow('⚠') +
3026
- ' A server is running but too old to report its version — restart it to finish the update.'
3027
- )
3028
- return
3029
- }
3030
- const target = expected ?? VERSION
3031
- if (info.version === target) {
3032
- if (expected) console.log(pc.green('✓') + ` Server already on v${info.version}`)
3033
- return
3034
- }
3035
- if (info.service) {
3036
- console.log(pc.dim(` restarting the service (server was v${info.version})…`))
3037
- try {
3038
- const fresh = await restartService()
3039
- if (fresh && fresh.version === target) {
3040
- console.log(pc.green('✓') + ` Service restarted on ${pc.bold('v' + fresh.version)}`)
3041
- } else if (fresh) {
3042
- console.log(
3043
- pc.yellow('⚠') +
3044
- ` Service restarted but reports v${fresh.version} (expected v${target}).` +
3045
- '\n' +
3046
- pc.dim(' The unit may exec a different install — see `moi service`.')
3047
- )
3048
- } else {
3049
- console.log(
3050
- pc.yellow('⚠') +
3051
- ' Service restarted but the server has not come back up — `moi service logs`.'
3052
- )
3053
- }
3054
- } catch (err) {
3055
- console.log(
3056
- pc.yellow('⚠') +
3057
- ' Could not restart the service: ' +
3058
- (err instanceof Error ? err.message : String(err))
3059
- )
3060
- }
3061
- return
3062
- }
3063
- console.log(
3064
- pc.yellow('⚠') +
3065
- ` A foreground server is still running v${info.version}` +
3066
- (info.pid ? pc.dim(` (pid ${info.pid})`) : '') +
3067
- '.\n' +
3068
- pc.dim(` Restart it when convenient (Ctrl-C, then \`moi start\`) to get v${target}.`)
3069
- )
3070
- }
3071
-
3072
- const version = defineCommand({
3073
- meta: { name: 'version', description: 'Print the moi version' },
3074
- run() {
3075
- console.log(versionWithCommit())
3076
- }
3077
- })
3078
-
3079
- // A static shell over ./cli-ui-components. The meta is inlined here because it
3080
- // is all the root help needs; the registry loader stays lazy until used.
3081
- const uiComponents = defineCommand({
3082
- meta: {
3083
- name: 'ui-components',
3084
- description: 'UI components for applets'
3085
- },
3086
- subCommands: () => import('./cli-ui-components').then(m => m.uiComponentsSubCommands),
3087
- async run({ rawArgs }) {
3088
- const { runUiComponentsCatalog } = await import('./cli-ui-components')
3089
- await runUiComponentsCatalog(rawArgs)
3090
- }
3091
- })
3092
-
3093
- // The root help splits the surface by audience: workspace commands are the
3094
- // agent's day-to-day toolkit (skills tell it to run them); system commands
3095
- // manage moi itself and are for the human at the keyboard.
3096
- const workspaceCommands = {
3097
- bundle,
3098
- check,
3099
- refresh,
3100
- builder,
3101
- 'call-server-fn': callServerFn,
3102
- debug,
3103
- theme,
3104
- config,
3105
- env,
3106
- scratch,
3107
- skill,
3108
- tabs,
3109
- navigate,
3110
- 'ui-components': uiComponents
3111
- }
3112
-
3113
- const systemCommands = {
3114
- init,
3115
- start,
3116
- status,
3117
- service,
3118
- update,
3119
- openclaw,
3120
- hermes,
3121
- version
3122
- }
3123
-
3124
- const main = defineCommand({
3125
- // A function so the git lookup runs only for `moi --version` / `--help`, not on
3126
- // every command. citty resolves a function meta (used for --version + usage).
3127
- meta: () => ({
3128
- name: 'moi',
3129
- description: 'moi — local AI workspace',
3130
- version: versionWithCommit()
3131
- }),
3132
- subCommands: { ...workspaceCommands, ...systemCommands }
3133
- })
3134
-
3135
- // Cloud demo: system commands manage moi itself (service, updates, agent
3136
- // runtimes) — in a demo container the instance is provisioned, not managed,
3137
- // so they print a pointer to the real thing instead of running. Two stay:
3138
- // `start`, because it is how the demo (container or a local test run) boots
3139
- // at all — against an already-running server it just reports and exits — and
3140
- // `version`, which is harmless and useful in bug reports.
3141
- function exitIfDemoBlocked(): void {
3142
- const invoked = process.argv[2]
3143
- if (!invoked || invoked === 'version' || invoked === 'start') return
3144
- if (!(invoked in systemCommands)) return
3145
- const config = getAppConfig()
3146
- if (!config.cloudDemo) return
3147
- console.log(
3148
- '\n' +
3149
- pc.yellow('◆') +
3150
- ` moi ${invoked} is not available in the demo.\n` +
3151
- pc.dim(' Get moi on your computer: ') +
3152
- pc.bold(config.demoInstallUrl) +
3153
- '\n'
3154
- )
3155
- process.exit(1)
3156
- }
3157
-
3158
- exitIfDemoBlocked()
3159
-
3160
- type HelpCommand = { meta?: unknown }
3161
-
3162
- async function commandDescription(cmd: HelpCommand): Promise<string> {
3163
- const meta = typeof cmd.meta === 'function' ? await cmd.meta() : await cmd.meta
3164
- return (meta as { description?: string })?.description ?? ''
3165
- }
3166
-
3167
- // Two-section root help (replaces citty's flat list). For a human, the
3168
- // system section carries an explicit note that agents should leave those
3169
- // commands alone; for a detected agent caller, the section is omitted
3170
- // entirely — an agent's `moi --help` shows only the workspace toolkit.
3171
- async function printMainHelp() {
3172
- const pad =
3173
- Math.max(...Object.keys({ ...workspaceCommands, ...systemCommands }).map(n => n.length)) + 4
3174
- const row = async (name: string, cmd: HelpCommand) =>
3175
- ' ' + pc.cyan(name.padEnd(pad)) + pc.dim(await commandDescription(cmd))
3176
- console.log()
3177
- console.log(
3178
- pc.bold('moi') + pc.dim(' — local AI workspace ') + pc.dim(`v${versionWithCommit()}`)
3179
- )
3180
- console.log()
3181
- console.log(pc.dim('USAGE ') + 'moi <command> [options]')
3182
- console.log()
3183
- console.log(pc.bold('Workspace commands:') + pc.dim(' for agents and humans alike'))
3184
- console.log()
3185
- for (const [name, cmd] of Object.entries(workspaceCommands)) console.log(await row(name, cmd))
3186
- console.log()
3187
- if (!isAgentCaller()) {
3188
- console.log(
3189
- pc.bold('System commands:') + pc.dim(' manage moi itself (server, service, updates)')
3190
- )
3191
- console.log(pc.yellow(' AGENTS: do not run these unless explicitly asked!'))
3192
- console.log()
3193
- for (const [name, cmd] of Object.entries(systemCommands)) console.log(await row(name, cmd))
3194
- console.log()
3195
- }
3196
- console.log(pc.dim('Use moi <command> --help for more information about a command.'))
3197
- console.log()
3198
- }
3199
-
3200
- // Route `moi --help` (and bare `moi`) to the two-section help, and
3201
- // `moi config --help` to its terse cheat sheet; every other command keeps
3202
- // citty's default usage renderer.
3203
- runMain(main, {
3204
- async showUsage(cmd, parent) {
3205
- const meta = typeof cmd.meta === 'function' ? await cmd.meta() : await cmd.meta
3206
- if (meta?.name === 'moi') {
3207
- await printMainHelp()
3208
- return
3209
- }
3210
- if (meta?.name === 'config') {
3211
- printConfigHelp()
3212
- return
3213
- }
3214
- await showUsage(cmd, parent)
3215
- }
3216
- })
2
+ import './cli/colors' // must precede citty: sets NO_COLOR before its color flag is computed
3
+ import './cli/index'