moi-computer 0.12.1-next.0 → 0.12.1-next.2

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