moi-computer 0.0.3 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (216) hide show
  1. package/README.md +2 -2
  2. package/bunfig.toml +4 -0
  3. package/client/api/workspaces.ts +277 -6
  4. package/client/assets/mcp/agentation.png +0 -0
  5. package/client/assets/mcp/airtable.png +0 -0
  6. package/client/assets/mcp/apollo.png +0 -0
  7. package/client/assets/mcp/asana.png +0 -0
  8. package/client/assets/mcp/box.png +0 -0
  9. package/client/assets/mcp/chrome.svg +33 -0
  10. package/client/assets/mcp/clickup.png +0 -0
  11. package/client/assets/mcp/cloudflare.png +0 -0
  12. package/client/assets/mcp/context7.png +0 -0
  13. package/client/assets/mcp/datadog.png +0 -0
  14. package/client/assets/mcp/dropbox.png +0 -0
  15. package/client/assets/mcp/elevenlabs.png +0 -0
  16. package/client/assets/mcp/exa.png +0 -0
  17. package/client/assets/mcp/firecrawl.png +0 -0
  18. package/client/assets/mcp/gmail.png +0 -0
  19. package/client/assets/mcp/googlecalendar.png +0 -0
  20. package/client/assets/mcp/googledrive.png +0 -0
  21. package/client/assets/mcp/grafana.png +0 -0
  22. package/client/assets/mcp/huggingface.png +0 -0
  23. package/client/assets/mcp/intercom.png +0 -0
  24. package/client/assets/mcp/monday.png +0 -0
  25. package/client/assets/mcp/mongodb.png +0 -0
  26. package/client/assets/mcp/paper.png +0 -0
  27. package/client/assets/mcp/paypal.png +0 -0
  28. package/client/assets/mcp/perplexity.png +0 -0
  29. package/client/assets/mcp/postgresql.png +0 -0
  30. package/client/assets/mcp/posthog.png +0 -0
  31. package/client/assets/mcp/puppeteer.png +0 -0
  32. package/client/assets/mcp/railway.png +0 -0
  33. package/client/assets/mcp/redis.png +0 -0
  34. package/client/assets/mcp/salesforce.png +0 -0
  35. package/client/assets/mcp/shopify.png +0 -0
  36. package/client/assets/mcp/snowflake.png +0 -0
  37. package/client/assets/mcp/telegram.png +0 -0
  38. package/client/assets/mcp/twilio.png +0 -0
  39. package/client/assets/mcp/zapier.png +0 -0
  40. package/client/components/App.tsx +7 -1
  41. package/client/components/ChatInput.tsx +194 -13
  42. package/client/components/ChatPanel.tsx +116 -47
  43. package/client/components/ChatPopup.tsx +1 -1
  44. package/client/components/IconMcp.tsx +21 -0
  45. package/client/components/McpMenu.tsx +125 -0
  46. package/client/components/ModelPicker.tsx +147 -0
  47. package/client/components/Scratchpad.tsx +775 -0
  48. package/client/components/ShimmerText.tsx +20 -0
  49. package/client/components/ThreadSelector.tsx +2 -2
  50. package/client/components/TurnView.tsx +111 -531
  51. package/client/components/WidgetShell.tsx +1 -1
  52. package/client/components/WorkspacesPage.tsx +12 -4
  53. package/client/components/layout/SidebarLayout.tsx +18 -9
  54. package/client/components/playground/ToolCallsPage.tsx +81 -0
  55. package/client/components/routes/workspace/[id].tsx +534 -141
  56. package/client/components/routes/workspace/create.tsx +155 -0
  57. package/client/components/settings/IconPicker.tsx +590 -0
  58. package/client/components/settings/SettingsPages.tsx +307 -0
  59. package/client/components/settings/WorkspaceSettings.tsx +92 -0
  60. package/client/components/tool-group/CodeBlock.tsx +41 -0
  61. package/client/components/tool-group/Collapse.tsx +28 -0
  62. package/client/components/tool-group/ReadImagePreview.tsx +46 -0
  63. package/client/components/tool-group/SubagentCard.tsx +135 -0
  64. package/client/components/tool-group/TimelineRow.tsx +147 -0
  65. package/client/components/tool-group/ToolCallGroup.tsx +231 -0
  66. package/client/components/tool-group/ToolOutput.tsx +139 -0
  67. package/client/components/tool-group/detect.ts +93 -0
  68. package/client/components/tool-group/fixtures.ts +315 -0
  69. package/client/components/tool-group/format.ts +211 -0
  70. package/client/components/tool-group/index.ts +9 -0
  71. package/client/components/ui/dialog.tsx +58 -0
  72. package/client/components/ui/hover-card.tsx +44 -0
  73. package/client/components/ui/switch.tsx +23 -0
  74. package/client/components/ui/tooltip.tsx +54 -0
  75. package/client/externalize-react.ts +6 -0
  76. package/client/hooks/useApplet.ts +117 -0
  77. package/client/hooks/useChat.ts +162 -62
  78. package/client/hooks/useMeiEvents.ts +9 -2
  79. package/client/hooks/useStickToBottom.ts +86 -0
  80. package/client/hooks/useWorkspaceTheme.ts +8 -2
  81. package/client/index.css +48 -2
  82. package/client/index.html +9 -5
  83. package/client/index.tsx +29 -2
  84. package/client/lib/WorkspaceContext.tsx +5 -8
  85. package/client/lib/WorkspaceLayoutContext.tsx +30 -10
  86. package/client/lib/applet-cache.ts +54 -0
  87. package/client/lib/connection.ts +237 -0
  88. package/client/lib/flags.ts +10 -0
  89. package/client/lib/mcp-icons.ts +142 -10
  90. package/client/lib/preview-turn.ts +37 -0
  91. package/client/lib/render-icon.ts +173 -0
  92. package/client/lib/scratch-executor.ts +20 -0
  93. package/client/lib/uploads.ts +18 -0
  94. package/client/main.tsx +5 -0
  95. package/client/store/live.ts +282 -0
  96. package/client/structured-clone-shim.ts +14 -0
  97. package/client/theme.css +2 -2
  98. package/client/vendor/emojibase/en/data.json +1 -0
  99. package/client/vendor/emojibase/en/messages.json +1 -0
  100. package/client/vendor/react/development/_impl/react-dom-client.js +15871 -0
  101. package/client/vendor/react/development/_impl/react-dom.js +223 -0
  102. package/client/vendor/react/development/_impl/react-jsx-dev-runtime.js +256 -0
  103. package/client/vendor/react/development/_impl/react-jsx-runtime.js +260 -0
  104. package/client/vendor/react/development/_impl/react.js +863 -0
  105. package/client/vendor/react/development/react-dom-client.js +6 -0
  106. package/client/vendor/react/development/react-dom.js +17 -0
  107. package/client/vendor/react/development/react-jsx-dev-runtime.js +5 -0
  108. package/client/vendor/react/development/react-jsx-runtime.js +6 -0
  109. package/client/vendor/react/development/react.js +47 -0
  110. package/client/vendor/react/production/_impl/react-dom-client.js +10361 -0
  111. package/client/vendor/react/production/_impl/react-dom.js +184 -0
  112. package/client/vendor/react/production/_impl/react-jsx-dev-runtime.js +37 -0
  113. package/client/vendor/react/production/_impl/react-jsx-runtime.js +60 -0
  114. package/client/vendor/react/production/_impl/react.js +428 -0
  115. package/client/vendor/react/production/react-dom-client.js +6 -0
  116. package/client/vendor/react/production/react-dom.js +17 -0
  117. package/client/vendor/react/production/react-jsx-dev-runtime.js +5 -0
  118. package/client/vendor/react/production/react-jsx-runtime.js +6 -0
  119. package/client/vendor/react/production/react.js +47 -0
  120. package/dist/agentation-4s0nn45p.png +0 -0
  121. package/dist/airtable-hsa66v6q.png +0 -0
  122. package/dist/apollo-2ed5dy2d.png +0 -0
  123. package/dist/asana-tvgtwbx2.png +0 -0
  124. package/dist/box-w3n36t5g.png +0 -0
  125. package/dist/chrome-tspm94rw.svg +33 -0
  126. package/dist/chunk-kc6e9nd4.css +1 -0
  127. package/dist/chunk-yf3p7qg7.js +673 -0
  128. package/dist/clickup-qqrqqvqb.png +0 -0
  129. package/dist/cloudflare-j9p931v6.png +0 -0
  130. package/dist/context7-8ht0xjfy.png +0 -0
  131. package/dist/datadog-70ne3yzt.png +0 -0
  132. package/dist/dropbox-4m5s9mgr.png +0 -0
  133. package/dist/elevenlabs-2nzzej1t.png +0 -0
  134. package/dist/exa-qqj3vr0x.png +0 -0
  135. package/dist/firecrawl-w2t8nehx.png +0 -0
  136. package/dist/gmail-sg6a5v3x.png +0 -0
  137. package/dist/googlecalendar-nqhh2v7r.png +0 -0
  138. package/dist/googledrive-6s8xyab7.png +0 -0
  139. package/dist/grafana-1yfsnwr6.png +0 -0
  140. package/dist/huggingface-kxzaxj83.png +0 -0
  141. package/dist/index.html +10 -6
  142. package/dist/intercom-td763jt8.png +0 -0
  143. package/dist/monday-jdbs4wwf.png +0 -0
  144. package/dist/mongodb-emzxvhd5.png +0 -0
  145. package/dist/paper-zbt34fab.png +0 -0
  146. package/dist/paypal-kwwf7xsc.png +0 -0
  147. package/dist/perplexity-4y63rxvj.png +0 -0
  148. package/dist/postgresql-qsspbsr1.png +0 -0
  149. package/dist/posthog-sphppc4w.png +0 -0
  150. package/dist/puppeteer-2xjt1a9b.png +0 -0
  151. package/dist/railway-834de8d2.png +0 -0
  152. package/dist/redis-spm6w2m1.png +0 -0
  153. package/dist/salesforce-1mk56v4z.png +0 -0
  154. package/dist/shopify-90dadaav.png +0 -0
  155. package/dist/snowflake-hfpykpgy.png +0 -0
  156. package/dist/telegram-v6tjyrs7.png +0 -0
  157. package/dist/twilio-dpyjdwpj.png +0 -0
  158. package/dist/zapier-p67qfch0.png +0 -0
  159. package/lib/attachment-note.ts +48 -0
  160. package/lib/claude-adapter.ts +219 -29
  161. package/lib/format.ts +32 -0
  162. package/lib/types.ts +314 -6
  163. package/package.json +11 -5
  164. package/server/CLAUDE.md +4 -1
  165. package/server/agent.ts +25 -118
  166. package/server/api.ts +593 -0
  167. package/server/applets.ts +396 -0
  168. package/server/build-applet.ts +580 -0
  169. package/server/cc-session.ts +611 -0
  170. package/server/cli-colors.ts +17 -0
  171. package/server/cli-ui.ts +52 -0
  172. package/server/cli.ts +965 -73
  173. package/server/constants.ts +1 -1
  174. package/server/control.ts +166 -19
  175. package/server/debug.ts +10 -0
  176. package/server/events.ts +24 -0
  177. package/server/functions-worker.ts +18 -2
  178. package/server/functions.ts +59 -12
  179. package/server/icon.ts +13 -0
  180. package/server/layout.ts +25 -3
  181. package/server/mcp.ts +125 -0
  182. package/server/moi-scaffold.ts +85 -0
  183. package/server/openclaw-session.ts +41 -10
  184. package/server/openclaw.ts +22 -0
  185. package/server/preview.ts +70 -0
  186. package/server/registry.ts +32 -2
  187. package/server/scratchpad-executor.ts +380 -0
  188. package/server/scratchpad-relay.ts +45 -0
  189. package/server/scratchpad.ts +171 -0
  190. package/server/skill-version.ts +146 -0
  191. package/server/skills-template.ts +6 -1
  192. package/server/state.ts +22 -36
  193. package/server/static.ts +23 -0
  194. package/server/status.ts +94 -0
  195. package/server/thread-config.ts +125 -0
  196. package/server/uploads.ts +0 -0
  197. package/server/vendor.ts +63 -0
  198. package/server/views.ts +0 -0
  199. package/server/web.ts +108 -253
  200. package/server/widgets.ts +52 -142
  201. package/server/workspace-config.ts +37 -0
  202. package/server/workspace-env.ts +407 -0
  203. package/server/workspace-init.ts +66 -0
  204. package/workspace/.claude/skills/moi-workspace/DESIGN.md +109 -0
  205. package/workspace/.claude/skills/moi-workspace/SCRATCHPAD.md +57 -0
  206. package/workspace/.claude/skills/moi-workspace/SKILL.md +252 -0
  207. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +22 -0
  208. package/client/hooks/useWidget.ts +0 -72
  209. package/client/hooks/useWidgetList.ts +0 -30
  210. package/client/lib/ws.ts +0 -129
  211. package/client/store/chat.tsx +0 -162
  212. package/dist/chunk-4615fa69.js +0 -67
  213. package/dist/chunk-582xmy05.css +0 -1
  214. package/server/build-widget.ts +0 -343
  215. package/workspace/.claude/skills/widgets/DESIGN.md +0 -630
  216. package/workspace/.claude/skills/widgets/SKILL.md +0 -176
package/server/cli.ts CHANGED
@@ -1,17 +1,37 @@
1
1
  #!/usr/bin/env bun
2
- import { defineCommand, runMain } from 'citty'
3
- import Table from 'cli-table3'
4
- import { mkdir } from 'node:fs/promises'
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 { existsSync } from 'node:fs'
5
+ import { tmpdir } from 'node:os'
5
6
  import { join, resolve } from 'path'
6
7
  import pc from 'picocolors'
7
8
 
8
9
  import { COLOR_THEMES, FONT_THEMES } from '@/lib/themes'
9
10
  import type { ColorTheme, FontTheme } from '@/lib/themes'
10
-
11
+ import type {
12
+ ScratchArrowEnd,
13
+ ScratchColor,
14
+ ScratchFill,
15
+ ScratchImageQuality,
16
+ ScratchOp,
17
+ ScratchSize,
18
+ ScratchStyle
19
+ } from '@/lib/types'
20
+
21
+ import { columns } from './cli-ui'
11
22
  import { CONTROL_PORT, PORT } from './constants'
12
23
  import { type OpenClawAgent, discoverOpenClawAgents } from './openclaw'
13
- import { registerWorkspace } from './registry'
24
+ import { liftToWorkspaceRoot, registerWorkspace } from './registry'
25
+ import {
26
+ type SkillStatus,
27
+ isBehind,
28
+ isMinorBehind,
29
+ resolveWorkspace,
30
+ skillStatuses,
31
+ staleSkillNotice
32
+ } from './skill-version'
14
33
  import { installBundledSkills } from './skills-template'
34
+ import { provisionWorkspace, skillsDirFor } from './workspace-init'
15
35
 
16
36
  // ---- helpers ----------------------------------------------------------------
17
37
 
@@ -158,18 +178,91 @@ const init = defineCommand({
158
178
  }
159
179
  },
160
180
  async run({ args }) {
161
- const target = resolve(args.dir)
181
+ const requested = resolve(args.dir)
182
+ // Locate the workspace root first: if invoked from inside a `.moi/` (or a
183
+ // deeper accidental `.moi/.moi/…`), lift to the directory that owns it
184
+ // instead of scaffolding a nested workspace. This is what stops the
185
+ // `.moi/.moi` bug at the source.
186
+ const target = liftToWorkspaceRoot(requested)
187
+ if (target !== requested) {
188
+ console.log(
189
+ '\n' +
190
+ pc.yellow('◆') +
191
+ ' Ran inside ' +
192
+ pc.bold('.moi') +
193
+ ' — using the workspace root ' +
194
+ pc.bold(target) +
195
+ ' instead (no nested .moi created).'
196
+ )
197
+ }
198
+ // Flag a stray nested `.moi/.moi` left by the old cwd bug — harmless but
199
+ // confusing, and easy to remove.
200
+ const stray = join(target, '.moi', '.moi')
201
+ if (existsSync(stray)) {
202
+ console.log(
203
+ '\n' +
204
+ pc.yellow('⚠') +
205
+ ' Found a stray nested ' +
206
+ pc.bold('.moi/.moi') +
207
+ ' (from an older bug). Safe to remove:\n' +
208
+ pc.dim(' rm -rf ' + stray)
209
+ )
210
+ }
211
+
162
212
  const projectRoot = join(import.meta.dir, '..')
163
213
  const isInteractive = process.stdout.isTTY
164
214
 
165
- await mkdir(target, { recursive: true })
166
- await installBundledSkills(join(target, '.claude', 'skills'))
215
+ // Detect an OpenClaw agent workspace before provisioning: skills must land
216
+ // in `skills/` (not `.claude/skills/`) and the registry entry must carry
217
+ // the agent metadata — same as `moi openclaw init <agent>`. Discovery
218
+ // returns [] when the gateway is down, so this never blocks a plain init.
219
+ const agent = (await discoverOpenClawAgents()).find(a => a.path === target) ?? null
220
+ if (agent) {
221
+ console.log(
222
+ '\n' +
223
+ pc.yellow('◆') +
224
+ ' Detected an OpenClaw agent workspace ' +
225
+ pc.dim('(' + agent.agentId + (agent.name ? ', ' + agent.name : '') + ')') +
226
+ ' — initializing for OpenClaw.'
227
+ )
228
+ }
229
+
230
+ // Provision: bundled skills + the `.moi/` bootstrap (widgets dir +
231
+ // package.json + bun install). An existing `.moi/` is left untouched.
232
+ console.log()
233
+ const { scaffold, skillsDir } = await provisionWorkspace(
234
+ target,
235
+ agent ? 'openclaw' : 'claude-code'
236
+ )
237
+ if (scaffold !== 'exists') {
238
+ console.log(pc.dim(' Installed widget dependencies in .moi/'))
239
+ if (scaffold !== 0) {
240
+ console.warn(pc.yellow(' bun install failed — run it manually in .moi/'))
241
+ }
242
+ }
167
243
 
168
244
  // Always register the workspace in the persistent registry
169
- const entry = await registerWorkspace(target)
245
+ const entry = await registerWorkspace(
246
+ target,
247
+ agent
248
+ ? {
249
+ type: 'openclaw',
250
+ name: agent.name,
251
+ agentId: agent.agentId,
252
+ isDefault: agent.isDefault,
253
+ lastRunAt: agent.lastRunAt
254
+ }
255
+ : { type: 'claude-code' }
256
+ )
170
257
 
171
- console.log('\n' + pc.green('✓') + ' Initialized ' + pc.bold(target))
172
- console.log(' Skills installed — ask Claude to build a widget to get started\n')
258
+ console.log(pc.green('✓') + ' Initialized ' + pc.bold(target))
259
+ console.log(
260
+ ' Skills installed to ' +
261
+ pc.dim(skillsDir) +
262
+ ' — ask ' +
263
+ (agent ? 'your agent' : 'Claude') +
264
+ ' to build a widget to get started\n'
265
+ )
173
266
 
174
267
  // If --web and server not running, start it (stay alive as wrapper)
175
268
  let running = await isServerRunning()
@@ -215,13 +308,16 @@ const start = defineCommand({
215
308
  args: {
216
309
  port: {
217
310
  type: 'string',
218
- description: 'HTTP port to listen on (default: 3000)'
311
+ description: 'HTTP port to listen on (default: 13337)'
219
312
  }
220
313
  },
221
314
  async run({ args }) {
222
315
  const projectRoot = join(import.meta.dir, '..')
223
316
  // Undocumented: --dev runs the watch-and-full-restart dev supervisor.
224
317
  const dev = process.argv.includes('--dev')
318
+ // Undocumented: --debug turns on the messaging trace (MOI_DEBUG) in the
319
+ // server — console lines for each message/session/turn in the chat pipeline.
320
+ const debug = process.argv.includes('--debug')
225
321
 
226
322
  // Launcher path: we are the CLI, not the server. Decide whether to bail
227
323
  // (a server is already up), run the dev supervisor, or spawn a one-shot
@@ -239,8 +335,16 @@ const start = defineCommand({
239
335
  // `dist/` exists in the tree (prod serves prebuilt `dist/` statically).
240
336
  const env = {
241
337
  ...process.env,
338
+ // The dev bundler snapshots process.env at server startup, so the
339
+ // PUBLIC_* inlining (bunfig `[serve.static] env`) only sees vars that
340
+ // are set before the server process spawns — setting one later from
341
+ // server code does nothing. Default the tldraw key here so an unset
342
+ // key inlines as '' (→ watermark) instead of leaving a bare
343
+ // `process.env.…` in the browser bundle that throws.
344
+ PUBLIC_TLDRAW_LICENSE_KEY: process.env.PUBLIC_TLDRAW_LICENSE_KEY ?? '',
242
345
  ...(args.port ? { PORT: args.port } : {}),
243
- ...(dev ? { MOI_DEV: '1' } : {})
346
+ ...(dev ? { MOI_DEV: '1' } : {}),
347
+ ...(debug ? { MOI_DEBUG: '1' } : {})
244
348
  }
245
349
  if (dev) {
246
350
  await runDevSupervisor(projectRoot, env)
@@ -266,7 +370,7 @@ function colorStatus(status: string) {
266
370
  }
267
371
 
268
372
  const bundle = defineCommand({
269
- meta: { name: 'bundle', description: 'Rebuild changed widgets' },
373
+ meta: { name: 'bundle', description: 'Rebuild changed widgets and views' },
270
374
  args: {
271
375
  dir: {
272
376
  type: 'positional',
@@ -275,37 +379,78 @@ const bundle = defineCommand({
275
379
  },
276
380
  force: {
277
381
  type: 'boolean',
278
- description: 'Rebuild all widgets, ignoring file modification times',
382
+ description: 'Rebuild everything, ignoring file modification times',
279
383
  default: false
384
+ },
385
+ only: {
386
+ type: 'string',
387
+ description: 'Narrow the build to "widgets" or "views" (default: both)'
280
388
  }
281
389
  },
282
- run({ args }) {
390
+ async run({ args }) {
283
391
  const path = resolve(args.dir)
392
+ // Computed locally up front so it can ride along in the success output; the
393
+ // agent reads this and knows to run `moi skill update`.
394
+ const notice = await staleSkillNotice(path)
284
395
  const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
285
396
 
286
- ws.onopen = () => ws.send(JSON.stringify({ type: 'bundle', path, force: args.force }))
397
+ ws.onopen = () =>
398
+ ws.send(JSON.stringify({ type: 'bundle', path, force: args.force, only: args.only }))
287
399
 
288
400
  ws.onmessage = event => {
289
- const results = JSON.parse(String(event.data))
290
- if (!Array.isArray(results)) return
401
+ const res = JSON.parse(String(event.data))
291
402
 
292
- const table = new Table({ head: [pc.bold('widget'), pc.bold('status')] })
293
- for (const r of results as { name: string; status: string; error?: string }[]) {
294
- table.push([r.name, colorStatus(r.status)])
403
+ // The server fails loudly when the path isn't inside a registered
404
+ // workspace (e.g. run from an unrelated dir) instead of silently no-op'ing.
405
+ if (res.error) {
406
+ console.error('\n' + pc.red(pc.bold('Error:')) + ' ' + res.error + '\n')
407
+ ws.close()
408
+ process.exit(1)
409
+ }
410
+
411
+ type Row = { kind?: string; name: string; status: string; error?: string }
412
+ const results: Row[] = Array.isArray(res.results) ? res.results : []
413
+ const where = typeof res.workspacePath === 'string' ? res.workspacePath : path
414
+
415
+ // Empty here means a *real* workspace with no widgets/views — not the old
416
+ // "wrong dir" footgun (that's an error above now). Say so plainly.
417
+ if (results.length === 0) {
418
+ console.log(
419
+ '\n' +
420
+ pc.bold('moi bundle') +
421
+ pc.dim(' — nothing to build') +
422
+ '\n\n' +
423
+ pc.dim(` No widgets or views found in ${where}/.moi/`) +
424
+ '\n'
425
+ )
426
+ if (notice) console.log(pc.yellow(notice) + '\n')
427
+ ws.close()
428
+ process.exit(0)
295
429
  }
296
- console.log('\n' + table.toString())
297
430
 
298
- const failed = results.filter(
299
- (r: { status: string; error?: string }) => r.status === 'failed'
431
+ const counts: Record<string, number> = {}
432
+ for (const r of results) counts[r.status] = (counts[r.status] ?? 0) + 1
433
+ const summary = ['built', 'skipped', 'failed']
434
+ .filter(s => counts[s])
435
+ .map(s => `${counts[s]} ${s}`)
436
+ .join(' · ')
437
+
438
+ console.log('\n' + pc.bold('moi bundle') + pc.dim(` — ${summary}`) + '\n')
439
+ console.log(
440
+ columns(
441
+ ['kind', 'name', 'status'].map(h => pc.dim(h)),
442
+ results.map(r => [pc.dim(r.kind ?? ''), r.name, colorStatus(r.status)])
443
+ )
300
444
  )
301
- if (failed.length) {
302
- console.log()
303
- for (const f of failed) {
304
- console.log(pc.red(pc.bold(f.name + ':')))
305
- console.log(' ' + f.error + '\n')
306
- }
445
+
446
+ const failed = results.filter(r => r.status === 'failed')
447
+ console.log()
448
+ for (const f of failed) {
449
+ console.log(pc.red(pc.bold(f.name + ':')))
450
+ console.log(' ' + f.error + '\n')
307
451
  }
308
452
 
453
+ if (notice) console.log(pc.yellow(notice) + '\n')
309
454
  ws.close()
310
455
  process.exit(failed.length > 0 ? 1 : 0)
311
456
  }
@@ -323,7 +468,8 @@ const refresh = defineCommand({
323
468
  description:
324
469
  'Refresh widget data without rebuilding. Use after the agent mutates underlying data.'
325
470
  },
326
- run() {
471
+ async run() {
472
+ const notice = await staleSkillNotice(process.cwd())
327
473
  const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
328
474
 
329
475
  ws.onopen = () => ws.send(JSON.stringify({ type: 'widget:refresh' }))
@@ -336,6 +482,7 @@ const refresh = defineCommand({
336
482
  process.exit(1)
337
483
  }
338
484
  console.log('\n' + pc.green('✓') + ' Refresh signal sent\n')
485
+ if (notice) console.log(pc.yellow(notice) + '\n')
339
486
  ws.close()
340
487
  process.exit(0)
341
488
  }
@@ -372,8 +519,9 @@ const theme = defineCommand({
372
519
  font: { type: 'string', description: 'Font theme key to apply' },
373
520
  color: { type: 'string', description: 'Color preset key to apply' }
374
521
  },
375
- run({ args }) {
522
+ async run({ args }) {
376
523
  const path = resolve(args.dir)
524
+ const notice = await staleSkillNotice(path)
377
525
  const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
378
526
 
379
527
  ws.onopen = () =>
@@ -412,6 +560,7 @@ const theme = defineCommand({
412
560
  console.log(pc.green('✓') + ' Color set to ' + pc.bold(preset.label) + ' ' + chip)
413
561
  }
414
562
  console.log()
563
+ if (notice) console.log(pc.yellow(notice) + '\n')
415
564
  ws.close()
416
565
  process.exit(0)
417
566
  }
@@ -421,43 +570,46 @@ const theme = defineCommand({
421
570
  console.log('\n' + pc.bold('moi theme') + ' — workspace appearance')
422
571
  console.log(pc.dim(' Usage: moi theme --font=<key> --color=<key>') + '\n')
423
572
 
424
- const fontTable = new Table({
425
- head: ['', 'key', 'label', 'sans', 'mono', 'feel'].map(h => pc.bold(h)),
426
- style: { border: [], head: [] }
427
- })
428
- for (const key of Object.keys(FONT_THEMES) as FontTheme[]) {
573
+ const fontRows = (Object.keys(FONT_THEMES) as FontTheme[]).map(key => {
429
574
  const f = FONT_THEMES[key]
430
575
  const selected = key === currentFont
431
- fontTable.push([
432
- selected ? pc.green('→') : '',
576
+ return [
577
+ selected ? pc.green('→') : ' ',
433
578
  selected ? pc.bold(key) : key,
434
579
  f.label,
435
580
  pc.dim(f.sans),
436
581
  pc.dim(f.mono),
437
582
  pc.dim(f.feel)
438
- ])
439
- }
583
+ ]
584
+ })
440
585
  console.log(pc.dim(' Fonts'))
441
- console.log(fontTable.toString() + '\n')
586
+ console.log(
587
+ columns(
588
+ ['', 'key', 'label', 'sans', 'mono', 'feel'].map(h => pc.dim(h)),
589
+ fontRows
590
+ ) + '\n'
591
+ )
442
592
 
443
- const colorTable = new Table({
444
- head: ['', 'key', 'label', 'swatch', 'feel'].map(h => pc.bold(h)),
445
- style: { border: [], head: [] }
446
- })
447
- for (const key of Object.keys(COLOR_THEMES) as ColorTheme[]) {
593
+ const colorRows = (Object.keys(COLOR_THEMES) as ColorTheme[]).map(key => {
448
594
  const c = COLOR_THEMES[key]
449
595
  const selected = key === currentColor
450
- colorTable.push([
451
- selected ? pc.green('→') : '',
596
+ return [
597
+ selected ? pc.green('→') : ' ',
452
598
  selected ? pc.bold(key) : key,
453
599
  c.label,
454
600
  swatch(c.background, c.foreground),
455
601
  pc.dim(c.feel)
456
- ])
457
- }
602
+ ]
603
+ })
458
604
  console.log(pc.dim(' Colors'))
459
- console.log(colorTable.toString() + '\n')
605
+ console.log(
606
+ columns(
607
+ ['', 'key', 'label', 'swatch', 'feel'].map(h => pc.dim(h)),
608
+ colorRows
609
+ ) + '\n'
610
+ )
460
611
 
612
+ if (notice) console.log(pc.yellow(notice) + '\n')
461
613
  ws.close()
462
614
  process.exit(0)
463
615
  }
@@ -473,6 +625,7 @@ const status = defineCommand({
473
625
  meta: { name: 'status', description: 'Show server status and registered workspaces' },
474
626
  async run() {
475
627
  const running = await isServerRunning()
628
+ const notice = await staleSkillNotice(process.cwd())
476
629
 
477
630
  if (!running) {
478
631
  console.log('\n' + pc.dim('○') + ' Server is ' + pc.bold('not running') + '\n')
@@ -505,6 +658,7 @@ const status = defineCommand({
505
658
  ws.onerror = () => reject(new Error('Could not connect to control server'))
506
659
  })
507
660
 
661
+ if (notice) console.log(pc.yellow(notice) + '\n')
508
662
  process.exit(0)
509
663
  }
510
664
  })
@@ -521,19 +675,17 @@ function findAgent(agents: OpenClawAgent[], query: string): OpenClawAgent | null
521
675
  }
522
676
 
523
677
  function printAgentTable(agents: OpenClawAgent[]) {
524
- const table = new Table({
525
- head: ['', pc.bold('agentId'), pc.bold('name'), pc.bold('workspace')],
526
- style: { border: [], head: [] }
527
- })
528
- for (const a of agents) {
529
- table.push([
530
- a.isDefault ? pc.green('●') : '',
531
- a.isDefault ? pc.bold(a.agentId) : a.agentId,
532
- a.name ?? pc.dim('—'),
533
- pc.dim(a.path)
534
- ])
535
- }
536
- console.log(table.toString())
678
+ console.log(
679
+ columns(
680
+ ['', 'agentId', 'name', 'workspace'].map(h => pc.dim(h)),
681
+ agents.map(a => [
682
+ a.isDefault ? pc.green('●') : ' ',
683
+ a.isDefault ? pc.bold(a.agentId) : a.agentId,
684
+ a.name ?? pc.dim('—'),
685
+ pc.dim(a.path)
686
+ ])
687
+ )
688
+ )
537
689
  }
538
690
 
539
691
  const openclawInit = defineCommand({
@@ -582,11 +734,18 @@ const openclawInit = defineCommand({
582
734
  process.exit(1)
583
735
  }
584
736
 
585
- // Copy each shipped skill folder into <agent-workspace>/skills/<name>/.
586
- // OpenClaw resolves <workspace>/skills with the highest precedence, so
587
- // these win over any same-named bundled or per-user skill.
588
- const skillsRoot = join(target.path, 'skills')
589
- await installBundledSkills(skillsRoot)
737
+ // Shared provisioning path with `moi init`: skills land in
738
+ // <agent-workspace>/skills/<name>/ (OpenClaw resolves <workspace>/skills
739
+ // with the highest precedence, so these win over any same-named bundled or
740
+ // per-user skill), plus the `.moi/` bootstrap — the widgets skill assumes
741
+ // the folder and its dependencies exist. Existing `.moi/` stays untouched.
742
+ const { scaffold, skillsDir: skillsRoot } = await provisionWorkspace(target.path, 'openclaw')
743
+ if (scaffold !== 'exists') {
744
+ console.log('\n' + pc.dim(' Installed widget dependencies in .moi/'))
745
+ if (scaffold !== 0) {
746
+ console.warn(pc.yellow(' bun install failed — run it manually in .moi/'))
747
+ }
748
+ }
590
749
 
591
750
  // Register in the moi registry so the agent's workspace appears in the
592
751
  // UI workspace list. Mirrors what `moi init` does for Claude Code.
@@ -630,9 +789,742 @@ const openclaw = defineCommand({
630
789
  subCommands: { init: openclawInit }
631
790
  })
632
791
 
792
+ async function sendConfig(payload: {
793
+ path: string
794
+ name?: string
795
+ iconPath?: string
796
+ clearName?: boolean
797
+ clearIcon?: boolean
798
+ }) {
799
+ const notice = await staleSkillNotice(payload.path)
800
+ const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
801
+ ws.onopen = () => ws.send(JSON.stringify({ type: 'config', ...payload }))
802
+ ws.onmessage = event => {
803
+ const res = JSON.parse(String(event.data))
804
+ if (res.error) {
805
+ console.error('\n' + pc.red(pc.bold('Error:')) + ' ' + res.error + '\n')
806
+ ws.close()
807
+ process.exit(1)
808
+ }
809
+ console.log()
810
+ if (res.ok) {
811
+ if (res.clearedName) console.log(pc.green('✓') + ' Name reset to ' + pc.dim('(folder name)'))
812
+ else if (res.name) console.log(pc.green('✓') + ' Name set to ' + pc.bold(res.name))
813
+ if (res.clearedIcon)
814
+ console.log(pc.green('✓') + ' Icon reset to ' + pc.dim('default (provider)'))
815
+ else if (res.icon) console.log(pc.green('✓') + ' Icon updated ' + pc.dim('(128×128 webp)'))
816
+ } else {
817
+ console.log(pc.bold('moi config') + ' — workspace identity\n')
818
+ console.log(
819
+ ' ' + pc.dim('name') + ' ' + (res.name ? pc.bold(res.name) : pc.dim('(folder name)'))
820
+ )
821
+ console.log(
822
+ ' ' +
823
+ pc.dim('icon') +
824
+ ' ' +
825
+ (res.hasIcon ? pc.green('custom') : pc.dim('default (provider)'))
826
+ )
827
+ }
828
+ console.log()
829
+ if (notice) console.log(pc.yellow(notice) + '\n')
830
+ ws.close()
831
+ process.exit(0)
832
+ }
833
+ ws.onerror = () => {
834
+ console.error('Could not connect to control server. Is the main process running?')
835
+ process.exit(1)
836
+ }
837
+ }
838
+
839
+ // A terse cheat sheet — one line per command — so an agent can grasp the
840
+ // surface at a glance instead of parsing citty's full ARGUMENTS/OPTIONS dump.
841
+ function printConfigHelp() {
842
+ const row = (cmd: string, desc: string) => ' ' + pc.cyan(cmd.padEnd(34)) + pc.dim(desc)
843
+ console.log()
844
+ console.log(pc.bold('moi config') + pc.dim(' — workspace name & icon'))
845
+ console.log()
846
+ console.log(row('moi config', 'Show current name & icon'))
847
+ console.log(row('moi config name "My WS"', 'Set the display name'))
848
+ console.log(row('moi config name --clear', 'Reset name to folder default'))
849
+ console.log(row('moi config icon ./logo.png', 'Set icon (png/jpg/gif/webp → 128×128 webp)'))
850
+ console.log(row('moi config icon --clear', 'Reset icon to provider default'))
851
+ console.log(row(' --dir <path>', 'Target workspace (default: current dir)'))
852
+ console.log()
853
+ }
854
+
855
+ const config = defineCommand({
856
+ meta: {
857
+ name: 'config',
858
+ description: 'Show or set the workspace name and icon (moi config [name|icon] <value>)'
859
+ },
860
+ args: {
861
+ field: {
862
+ type: 'positional',
863
+ required: false,
864
+ description: '"name" or "icon" — omit to show the current config'
865
+ },
866
+ value: {
867
+ type: 'positional',
868
+ required: false,
869
+ description: 'The new name, or a path to an image file (png/jpg/gif/webp)'
870
+ },
871
+ clear: {
872
+ type: 'boolean',
873
+ description: 'Reset the field to its default (folder name / provider icon)'
874
+ },
875
+ dir: { type: 'string', default: '.', description: 'Workspace directory (default: current)' }
876
+ },
877
+ run({ args }) {
878
+ const path = resolve(args.dir)
879
+ if (args.field === 'help') {
880
+ printConfigHelp()
881
+ return
882
+ }
883
+ if (!args.field) {
884
+ sendConfig({ path })
885
+ return
886
+ }
887
+ if (args.field === 'name') {
888
+ if (args.clear) {
889
+ sendConfig({ path, clearName: true })
890
+ return
891
+ }
892
+ if (!args.value) {
893
+ console.error(pc.red('Usage:') + ' moi config name "<workspace name>"')
894
+ process.exit(1)
895
+ }
896
+ sendConfig({ path, name: args.value })
897
+ } else if (args.field === 'icon') {
898
+ if (args.clear) {
899
+ sendConfig({ path, clearIcon: true })
900
+ return
901
+ }
902
+ if (!args.value) {
903
+ console.error(pc.red('Usage:') + ' moi config icon <path-to-image>')
904
+ process.exit(1)
905
+ }
906
+ sendConfig({ path, iconPath: resolve(args.value) })
907
+ } else {
908
+ console.error(
909
+ pc.red(`Unknown field "${args.field}".`) +
910
+ ' Use ' +
911
+ pc.bold('name') +
912
+ ' or ' +
913
+ pc.bold('icon') +
914
+ '.'
915
+ )
916
+ process.exit(1)
917
+ }
918
+ }
919
+ })
920
+
921
+ // ---- scratch (Scratchpad canvas) --------------------------------------------
922
+
923
+ // Parse a "x,y" coordinate pair (tldraw canvas space, y down).
924
+ function parseXY(s: string): { x: number; y: number } {
925
+ const parts = s.split(',').map(p => Number(p.trim()))
926
+ if (parts.length !== 2 || !parts.every(n => Number.isFinite(n))) {
927
+ throw new Error(`Expected "x,y", got "${s}"`)
928
+ }
929
+ return { x: parts[0], y: parts[1] }
930
+ }
931
+
932
+ // An arrow endpoint: a bare "x,y" is a free point; anything else is a shape name
933
+ // to bind to (so the arrow follows that shape).
934
+ function parseEnd(s: string): ScratchArrowEnd {
935
+ if (/^-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?$/.test(s)) return parseXY(s)
936
+ return { name: s }
937
+ }
938
+
939
+ // The Scratchpad palette (matches the UI toolbar's six swatches) and each color's
940
+ // light-theme solid hex — used to snap an arbitrary `--color #rrggbb` to the nearest
941
+ // palette entry (tldraw shapes can't hold free hex). Keep in sync with the swatches
942
+ // in client/components/Scratchpad.tsx.
943
+ const COLOR_HEX: Record<ScratchColor, string> = {
944
+ black: '#1d1d1d',
945
+ red: '#e03131',
946
+ yellow: '#f1ac4b',
947
+ green: '#099268',
948
+ blue: '#4465e9',
949
+ grey: '#9fa8b2'
950
+ }
951
+ const COLOR_NAMES = Object.keys(COLOR_HEX) as ScratchColor[]
952
+
953
+ // Arrows expose tldraw's size as a line weight; the CLI mirrors the UI's two sizes.
954
+ const STROKE_SIZES: Record<string, ScratchSize> = { small: 'm', large: 'xl' }
955
+ const STROKE_NAMES = Object.keys(STROKE_SIZES)
956
+
957
+ // Text & notes expose the same size style as a label font size, under friendlier names.
958
+ const FONT_SIZES: Record<string, ScratchSize> = { regular: 'm', big: 'xl' }
959
+ const FONT_SIZE_NAMES = Object.keys(FONT_SIZES)
960
+
961
+ // Rectangle fills — the UI toolbar's four options. Each user-facing name maps onto a
962
+ // tldraw DefaultFillStyle value (see ScratchFill for tldraw's semi/solid quirk). Keep
963
+ // in sync with FILL_OPTIONS in client/components/Scratchpad.tsx.
964
+ const FILL_STYLES: Record<string, ScratchFill> = {
965
+ none: 'none',
966
+ semi: 'solid',
967
+ pattern: 'pattern',
968
+ solid: 'fill'
969
+ }
970
+ const FILL_NAMES = Object.keys(FILL_STYLES)
971
+
972
+ function hexToRgb(hex: string): [number, number, number] | null {
973
+ let h = hex.trim().replace(/^#/, '')
974
+ if (h.length === 3) h = h.replace(/(.)/g, '$1$1')
975
+ if (!/^[0-9a-fA-F]{6}$/.test(h)) return null
976
+ return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)]
977
+ }
978
+
979
+ // Accept a palette name as-is, or snap any hex to the nearest palette color by
980
+ // squared RGB distance. Throws on anything else.
981
+ function parseColor(s: string): ScratchColor {
982
+ const lower = s.trim().toLowerCase()
983
+ if ((COLOR_NAMES as string[]).includes(lower)) return lower as ScratchColor
984
+ const rgb = hexToRgb(s)
985
+ if (!rgb) {
986
+ throw new Error(
987
+ `Unknown color "${s}". Use a hex like "#4465e9" or one of: ${COLOR_NAMES.join(', ')}.`
988
+ )
989
+ }
990
+ let best: ScratchColor = 'black'
991
+ let bestDist = Infinity
992
+ for (const name of COLOR_NAMES) {
993
+ const [r, g, b] = hexToRgb(COLOR_HEX[name])!
994
+ const d = (r - rgb[0]) ** 2 + (g - rgb[1]) ** 2 + (b - rgb[2]) ** 2
995
+ if (d < bestDist) {
996
+ bestDist = d
997
+ best = name
998
+ }
999
+ }
1000
+ return best
1001
+ }
1002
+
1003
+ function parseStroke(s: string): ScratchSize {
1004
+ const size = STROKE_SIZES[s.trim().toLowerCase()]
1005
+ if (!size) throw new Error(`Unknown stroke "${s}". Use one of: ${STROKE_NAMES.join(', ')}.`)
1006
+ return size
1007
+ }
1008
+
1009
+ function parseFontSize(s: string): ScratchSize {
1010
+ const size = FONT_SIZES[s.trim().toLowerCase()]
1011
+ if (!size) throw new Error(`Unknown font size "${s}". Use one of: ${FONT_SIZE_NAMES.join(', ')}.`)
1012
+ return size
1013
+ }
1014
+
1015
+ function parseFill(s: string): ScratchFill {
1016
+ const fill = FILL_STYLES[s.trim().toLowerCase()]
1017
+ if (!fill) throw new Error(`Unknown fill "${s}". Use one of: ${FILL_NAMES.join(', ')}.`)
1018
+ return fill
1019
+ }
1020
+
1021
+ // Resize preset for `add image` — defaults to 'lo' (keep the canvas light).
1022
+ function parseImageQuality(s: string | undefined): ScratchImageQuality {
1023
+ if (!s) return 'lo'
1024
+ const q = s.trim().toLowerCase()
1025
+ if (q === 'lo' || q === 'hi') return q
1026
+ throw new Error(`Unknown quality "${s}". Use "lo" or "hi".`)
1027
+ }
1028
+
1029
+ // Optional styling shared across `add` commands — each command wires in only the
1030
+ // controls its shape exposes (mirroring the UI's per-tool style bar).
1031
+ const colorArg = {
1032
+ type: 'string',
1033
+ description: `Color: ${COLOR_NAMES.join(', ')}, or any hex (snapped to nearest)`
1034
+ } as const
1035
+ const strokeArg = {
1036
+ type: 'string',
1037
+ description: `Stroke weight: ${STROKE_NAMES.join(', ')}`
1038
+ } as const
1039
+ const fontSizeArg = {
1040
+ type: 'string',
1041
+ description: `Font size: ${FONT_SIZE_NAMES.join(', ')}`
1042
+ } as const
1043
+ const fillArg = {
1044
+ type: 'string',
1045
+ default: 'semi',
1046
+ description: `Fill: ${FILL_NAMES.join(', ')} (default: semi)`
1047
+ } as const
1048
+
1049
+ // Build the optional style props from raw args. `stroke` and `fontSize` are two names
1050
+ // for the same tldraw size style, so at most one is wired per command.
1051
+ function styleArgs(args: {
1052
+ color?: string
1053
+ stroke?: string
1054
+ fontSize?: string
1055
+ fill?: string
1056
+ }): ScratchStyle {
1057
+ return {
1058
+ ...(args.color ? { color: parseColor(args.color) } : {}),
1059
+ ...(args.stroke ? { size: parseStroke(args.stroke) } : {}),
1060
+ ...(args.fontSize ? { size: parseFontSize(args.fontSize) } : {}),
1061
+ ...(args.fill ? { fill: parseFill(args.fill) } : {})
1062
+ }
1063
+ }
1064
+
1065
+ type ScratchCliOp = ScratchOp | { kind: 'read' } | { kind: 'read-image'; name: string }
1066
+
1067
+ // Round-trip one op through the control port and hand the reply to `onResult`.
1068
+ // Mirrors the `bundle`/`theme` commands: one socket per invocation, print, exit.
1069
+ function sendScratch(
1070
+ path: string,
1071
+ op: ScratchCliOp,
1072
+ onResult: (res: Record<string, unknown>) => void | Promise<void>
1073
+ ) {
1074
+ const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
1075
+ ws.onopen = () => ws.send(JSON.stringify({ type: 'scratch', path, op }))
1076
+ ws.onmessage = async event => {
1077
+ const res = JSON.parse(String(event.data))
1078
+ if (res.error) {
1079
+ console.error('\n' + pc.red('✗') + ' ' + res.error + '\n')
1080
+ ws.close()
1081
+ process.exit(1)
1082
+ }
1083
+ await onResult(res)
1084
+ // The stale-skill notice rides on stderr so it never corrupts a command's
1085
+ // structured stdout (read's JSON, view's PNG path) while the agent still sees it.
1086
+ const notice = await staleSkillNotice(path)
1087
+ if (notice) console.error('\n' + pc.yellow(notice) + '\n')
1088
+ ws.close()
1089
+ process.exit(0)
1090
+ }
1091
+ ws.onerror = () => {
1092
+ console.error('Could not connect to control server. Is the main process running?')
1093
+ process.exit(1)
1094
+ }
1095
+ }
1096
+
1097
+ // Print the name a draw op landed on, so the agent can address it later.
1098
+ function printAdded(res: Record<string, unknown>) {
1099
+ const result = res.result as { name?: string } | undefined
1100
+ console.log('\n' + pc.green('✓') + ' added ' + pc.bold(result?.name ?? '(shape)') + '\n')
1101
+ }
1102
+
1103
+ const dirArg = {
1104
+ type: 'string',
1105
+ default: '.',
1106
+ description: 'Workspace directory (default: current)'
1107
+ } as const
1108
+
1109
+ const scratchRead = defineCommand({
1110
+ meta: { name: 'read', description: 'Print the canvas shapes as JSON (served off disk)' },
1111
+ args: { dir: dirArg },
1112
+ run({ args }) {
1113
+ sendScratch(resolve(args.dir), { kind: 'read' }, res => {
1114
+ console.log(JSON.stringify(res.shapes ?? [], null, 2))
1115
+ })
1116
+ }
1117
+ })
1118
+
1119
+ const scratchView = defineCommand({
1120
+ meta: { name: 'view', description: 'Render the canvas to a PNG (needs an open Scratchpad tab)' },
1121
+ args: {
1122
+ dir: dirArg,
1123
+ out: { type: 'string', description: 'Output PNG path (default: a temp file)' }
1124
+ },
1125
+ async run({ args }) {
1126
+ sendScratch(resolve(args.dir), { kind: 'view' }, async res => {
1127
+ const result = res.result as { image?: string } | undefined
1128
+ if (!result?.image) {
1129
+ console.error(pc.red('No image returned'))
1130
+ process.exit(1)
1131
+ }
1132
+ const b64 = result.image.replace(/^data:image\/png;base64,/, '')
1133
+ const outPath = args.out ? resolve(args.out) : join(tmpdir(), `moi-scratch-${Date.now()}.png`)
1134
+ await Bun.write(outPath, Buffer.from(b64, 'base64'))
1135
+ console.log(outPath)
1136
+ })
1137
+ }
1138
+ })
1139
+
1140
+ // Image data URL mime → file extension, for naming the saved file.
1141
+ const IMAGE_EXT: Record<string, string> = {
1142
+ 'image/png': 'png',
1143
+ 'image/jpeg': 'jpg',
1144
+ 'image/jpg': 'jpg',
1145
+ 'image/webp': 'webp',
1146
+ 'image/gif': 'gif',
1147
+ 'image/svg+xml': 'svg'
1148
+ }
1149
+
1150
+ const scratchReadImage = defineCommand({
1151
+ meta: {
1152
+ name: 'read-image',
1153
+ description: 'Save an image shape to a file by id (served off disk)'
1154
+ },
1155
+ args: {
1156
+ id: { type: 'positional', required: true, description: 'Image shape id (from `scratch read`)' },
1157
+ out: { type: 'string', description: 'Output file path (default: a temp file)' },
1158
+ dir: dirArg
1159
+ },
1160
+ async run({ args }) {
1161
+ sendScratch(resolve(args.dir), { kind: 'read-image', name: args.id }, async res => {
1162
+ const src = res.src as string | undefined
1163
+ if (!src) {
1164
+ console.error(pc.red('No image data'))
1165
+ process.exit(1)
1166
+ }
1167
+ // A remote (http) asset has no local bytes to write — just print the URL.
1168
+ if (/^https?:\/\//.test(src)) {
1169
+ console.log(src)
1170
+ return
1171
+ }
1172
+ const m = src.match(/^data:([^;,]+)(;base64)?,(.*)$/s)
1173
+ if (!m) {
1174
+ console.error(pc.red('Unrecognized image source'))
1175
+ process.exit(1)
1176
+ }
1177
+ const [, mime, base64, data] = m
1178
+ const bytes = base64
1179
+ ? Buffer.from(data, 'base64')
1180
+ : Buffer.from(decodeURIComponent(data), 'utf8')
1181
+ const ext = IMAGE_EXT[mime] ?? 'bin'
1182
+ const safeId = args.id.replace(/[^a-zA-Z0-9_-]/g, '_')
1183
+ const outPath = args.out
1184
+ ? resolve(args.out)
1185
+ : join(tmpdir(), `moi-scratch-${safeId}-${Date.now()}.${ext}`)
1186
+ await Bun.write(outPath, bytes)
1187
+ console.log(outPath)
1188
+ })
1189
+ }
1190
+ })
1191
+
1192
+ const scratchAddText = defineCommand({
1193
+ meta: { name: 'text', description: 'Add a text shape' },
1194
+ args: {
1195
+ at: { type: 'string', required: true, description: 'Position "x,y"' },
1196
+ text: { type: 'string', required: true, description: 'Text content' },
1197
+ id: { type: 'string', description: 'Stable name to address this shape later' },
1198
+ color: colorArg,
1199
+ fontSize: fontSizeArg,
1200
+ dir: dirArg
1201
+ },
1202
+ run({ args }) {
1203
+ const { x, y } = parseXY(args.at)
1204
+ sendScratch(
1205
+ resolve(args.dir),
1206
+ {
1207
+ kind: 'add-text',
1208
+ name: args.id ?? '',
1209
+ x,
1210
+ y,
1211
+ text: args.text,
1212
+ ...styleArgs({ color: args.color, fontSize: args.fontSize })
1213
+ },
1214
+ printAdded
1215
+ )
1216
+ }
1217
+ })
1218
+
1219
+ const scratchAddRect = defineCommand({
1220
+ meta: { name: 'rect', description: 'Add a rectangle' },
1221
+ args: {
1222
+ at: { type: 'string', required: true, description: 'Top-left position "x,y"' },
1223
+ size: { type: 'string', required: true, description: 'Size "w,h"' },
1224
+ text: { type: 'string', description: 'Optional label' },
1225
+ id: { type: 'string', description: 'Stable name to address this shape later' },
1226
+ color: colorArg,
1227
+ fill: fillArg,
1228
+ fontSize: fontSizeArg,
1229
+ dir: dirArg
1230
+ },
1231
+ run({ args }) {
1232
+ const { x, y } = parseXY(args.at)
1233
+ const { x: w, y: h } = parseXY(args.size)
1234
+ sendScratch(
1235
+ resolve(args.dir),
1236
+ {
1237
+ kind: 'add-rect',
1238
+ name: args.id ?? '',
1239
+ x,
1240
+ y,
1241
+ w,
1242
+ h,
1243
+ ...(args.text ? { text: args.text } : {}),
1244
+ ...styleArgs({ color: args.color, fill: args.fill, fontSize: args.fontSize })
1245
+ },
1246
+ printAdded
1247
+ )
1248
+ }
1249
+ })
1250
+
1251
+ const scratchAddNote = defineCommand({
1252
+ meta: { name: 'note', description: 'Add a sticky note' },
1253
+ args: {
1254
+ at: { type: 'string', required: true, description: 'Position "x,y"' },
1255
+ text: { type: 'string', required: true, description: 'Note content' },
1256
+ id: { type: 'string', description: 'Stable name to address this shape later' },
1257
+ color: colorArg,
1258
+ fontSize: fontSizeArg,
1259
+ dir: dirArg
1260
+ },
1261
+ run({ args }) {
1262
+ const { x, y } = parseXY(args.at)
1263
+ sendScratch(
1264
+ resolve(args.dir),
1265
+ {
1266
+ kind: 'add-note',
1267
+ name: args.id ?? '',
1268
+ x,
1269
+ y,
1270
+ text: args.text,
1271
+ ...styleArgs({ color: args.color, fontSize: args.fontSize })
1272
+ },
1273
+ printAdded
1274
+ )
1275
+ }
1276
+ })
1277
+
1278
+ const scratchAddArrow = defineCommand({
1279
+ meta: { name: 'arrow', description: 'Add an arrow connecting shapes or points' },
1280
+ args: {
1281
+ from: { type: 'string', required: true, description: 'Start: a shape name or "x,y"' },
1282
+ to: { type: 'string', required: true, description: 'End: a shape name or "x,y"' },
1283
+ id: { type: 'string', description: 'Stable name to address this shape later' },
1284
+ elbow: {
1285
+ type: 'boolean',
1286
+ description: 'Right-angle (squared) routing for diagrams; default is a curved arc'
1287
+ },
1288
+ color: colorArg,
1289
+ stroke: strokeArg,
1290
+ dir: dirArg
1291
+ },
1292
+ run({ args }) {
1293
+ sendScratch(
1294
+ resolve(args.dir),
1295
+ {
1296
+ kind: 'add-arrow',
1297
+ name: args.id ?? '',
1298
+ from: parseEnd(args.from),
1299
+ to: parseEnd(args.to),
1300
+ ...(args.elbow ? { elbow: true } : {}),
1301
+ ...styleArgs({ color: args.color, stroke: args.stroke })
1302
+ },
1303
+ printAdded
1304
+ )
1305
+ }
1306
+ })
1307
+
1308
+ const scratchAddImage = defineCommand({
1309
+ meta: { name: 'image', description: 'Add an image from a file (resized to fit the canvas)' },
1310
+ args: {
1311
+ path: {
1312
+ type: 'positional',
1313
+ required: true,
1314
+ description: 'Path to an image file (png/jpg/webp/gif)'
1315
+ },
1316
+ at: { type: 'string', description: 'Top-left position "x,y" (default: 0,0)' },
1317
+ id: { type: 'string', description: 'Stable name to address this shape later' },
1318
+ quality: { type: 'string', description: 'Resize: lo (default, smaller) or hi (sharper)' },
1319
+ dir: dirArg
1320
+ },
1321
+ run({ args }) {
1322
+ const { x, y } = args.at ? parseXY(args.at) : { x: 0, y: 0 }
1323
+ sendScratch(
1324
+ resolve(args.dir),
1325
+ {
1326
+ kind: 'add-image',
1327
+ name: args.id ?? '',
1328
+ x,
1329
+ y,
1330
+ path: resolve(args.path),
1331
+ quality: parseImageQuality(args.quality)
1332
+ },
1333
+ printAdded
1334
+ )
1335
+ }
1336
+ })
1337
+
1338
+ const scratchAdd = defineCommand({
1339
+ meta: { name: 'add', description: 'Add a shape: text, rect, note, arrow, or image' },
1340
+ subCommands: {
1341
+ text: scratchAddText,
1342
+ rect: scratchAddRect,
1343
+ note: scratchAddNote,
1344
+ arrow: scratchAddArrow,
1345
+ image: scratchAddImage
1346
+ }
1347
+ })
1348
+
1349
+ const scratchMove = defineCommand({
1350
+ meta: { name: 'move', description: 'Move a shape to a new position' },
1351
+ args: {
1352
+ id: { type: 'positional', required: true, description: 'Shape name' },
1353
+ to: { type: 'string', required: true, description: 'New position "x,y"' },
1354
+ dir: dirArg
1355
+ },
1356
+ run({ args }) {
1357
+ const { x, y } = parseXY(args.to)
1358
+ sendScratch(resolve(args.dir), { kind: 'move', name: args.id, x, y }, () =>
1359
+ console.log('\n' + pc.green('✓') + ' moved ' + pc.bold(args.id) + '\n')
1360
+ )
1361
+ }
1362
+ })
1363
+
1364
+ const scratchSet = defineCommand({
1365
+ meta: { name: 'set', description: "Relabel / edit a shape's text" },
1366
+ args: {
1367
+ id: { type: 'positional', required: true, description: 'Shape name' },
1368
+ text: { type: 'string', required: true, description: 'New text' },
1369
+ dir: dirArg
1370
+ },
1371
+ run({ args }) {
1372
+ sendScratch(resolve(args.dir), { kind: 'set', name: args.id, text: args.text }, () =>
1373
+ console.log('\n' + pc.green('✓') + ' updated ' + pc.bold(args.id) + '\n')
1374
+ )
1375
+ }
1376
+ })
1377
+
1378
+ const scratchDelete = defineCommand({
1379
+ meta: { name: 'delete', description: 'Delete a shape' },
1380
+ args: {
1381
+ id: { type: 'positional', required: true, description: 'Shape name' },
1382
+ dir: dirArg
1383
+ },
1384
+ run({ args }) {
1385
+ sendScratch(resolve(args.dir), { kind: 'delete', name: args.id }, () =>
1386
+ console.log('\n' + pc.green('✓') + ' deleted ' + pc.bold(args.id) + '\n')
1387
+ )
1388
+ }
1389
+ })
1390
+
1391
+ const scratchClear = defineCommand({
1392
+ meta: { name: 'clear', description: 'Delete every shape — wipe the whole canvas' },
1393
+ args: { dir: dirArg },
1394
+ run({ args }) {
1395
+ sendScratch(resolve(args.dir), { kind: 'clear' }, () =>
1396
+ console.log('\n' + pc.green('✓') + ' cleared the canvas\n')
1397
+ )
1398
+ }
1399
+ })
1400
+
1401
+ const scratch = defineCommand({
1402
+ meta: {
1403
+ name: 'scratch',
1404
+ description: 'Read and draw on the workspace Scratchpad canvas'
1405
+ },
1406
+ subCommands: {
1407
+ read: scratchRead,
1408
+ 'read-image': scratchReadImage,
1409
+ view: scratchView,
1410
+ add: scratchAdd,
1411
+ move: scratchMove,
1412
+ set: scratchSet,
1413
+ delete: scratchDelete,
1414
+ clear: scratchClear
1415
+ }
1416
+ })
1417
+
1418
+ // Re-copy bundled skills into a workspace, then report what changed. Pure
1419
+ // filesystem op — no running server needed. Resolves the workspace root the
1420
+ // same way `moi bundle` does, so it works from `.moi/` or any subdirectory.
1421
+ async function runSkillUpdate(cwd: string): Promise<void> {
1422
+ // Type-aware: an OpenClaw workspace keeps its skills in `skills/`, so the
1423
+ // update must target the same dir the agent actually loads from.
1424
+ const { root, type } = await resolveWorkspace(cwd)
1425
+ const before = await skillStatuses(root, type)
1426
+ await installBundledSkills(skillsDirFor(root, type))
1427
+ const after = await skillStatuses(root, type)
1428
+
1429
+ console.log('\n' + pc.green('✓') + ' Skills updated in ' + pc.bold(root) + '\n')
1430
+ console.log(
1431
+ columns(
1432
+ ['skill', 'from', 'to'].map(h => pc.dim(h)),
1433
+ after.map(s => {
1434
+ const prev = before.find(b => b.name === s.name)?.installed ?? null
1435
+ const changed = prev !== s.installed
1436
+ return [
1437
+ s.name,
1438
+ prev ?? pc.dim('none'),
1439
+ changed ? pc.green(s.installed ?? '?') : pc.dim((s.installed ?? '?') + ' (no change)')
1440
+ ]
1441
+ })
1442
+ )
1443
+ )
1444
+ console.log(
1445
+ '\n' +
1446
+ pc.dim(
1447
+ ' Changes apply when the skill is next loaded (new session or next skill invocation).'
1448
+ ) +
1449
+ '\n'
1450
+ )
1451
+ }
1452
+
1453
+ // Colored status label for one skill row: minor+ behind is actionable, a patch
1454
+ // gap is informational, otherwise current.
1455
+ function skillState(s: SkillStatus): string {
1456
+ if (isMinorBehind(s.installed, s.bundled)) return pc.yellow('update available')
1457
+ if (isBehind(s.installed, s.bundled)) return pc.dim('patch behind')
1458
+ return pc.green('up to date')
1459
+ }
1460
+
1461
+ // `update` and `install` are the same operation under two names (install kept
1462
+ // for symmetry with how skills first land in a workspace). `dir` is a `--dir`
1463
+ // option, not a positional: citty treats a bare positional on a command that
1464
+ // carries subcommands as an unknown subcommand. Reuses the shared `dirArg`.
1465
+ const defineSkillUpdate = (name: string, description: string) =>
1466
+ defineCommand({
1467
+ meta: { name, description },
1468
+ args: { dir: dirArg },
1469
+ async run({ args }) {
1470
+ await runSkillUpdate(resolve(args.dir))
1471
+ }
1472
+ })
1473
+
1474
+ const skillSubCommands = {
1475
+ update: defineSkillUpdate(
1476
+ 'update',
1477
+ 'Update this workspace’s skills to the version shipped with the CLI'
1478
+ ),
1479
+ install: defineSkillUpdate('install', 'Alias for `moi skill update`')
1480
+ }
1481
+
1482
+ const skill = defineCommand({
1483
+ meta: { name: 'skill', description: 'Show or update the workspace skills shipped with moi' },
1484
+ subCommands: skillSubCommands,
1485
+ args: { dir: dirArg },
1486
+ async run({ args, rawArgs }) {
1487
+ // citty runs this parent handler even after dispatching a subcommand, so
1488
+ // bail when one was given — otherwise `moi skill update` also prints status.
1489
+ const sub = rawArgs.find(a => !a.startsWith('-'))
1490
+ if (sub && sub in skillSubCommands) return
1491
+
1492
+ const { root, type } = await resolveWorkspace(resolve(args.dir))
1493
+ const statuses = await skillStatuses(root, type)
1494
+
1495
+ console.log('\n' + pc.bold('moi skill') + pc.dim(' — workspace skills') + '\n')
1496
+ console.log(
1497
+ columns(
1498
+ ['skill', 'installed', 'bundled', 'status'].map(h => pc.dim(h)),
1499
+ statuses.map(s => [
1500
+ s.name,
1501
+ s.installed ?? pc.dim('—'),
1502
+ s.bundled ?? pc.dim('—'),
1503
+ skillState(s)
1504
+ ])
1505
+ )
1506
+ )
1507
+ if (statuses.some(s => isBehind(s.installed, s.bundled))) {
1508
+ console.log('\n' + pc.dim(' Run ') + pc.bold('moi skill update') + pc.dim(' to refresh.'))
1509
+ }
1510
+ console.log()
1511
+ }
1512
+ })
1513
+
633
1514
  const main = defineCommand({
634
1515
  meta: { name: 'moi', description: 'moi — local AI workspace' },
635
- subCommands: { init, start, bundle, refresh, theme, status, openclaw }
1516
+ subCommands: { init, start, bundle, refresh, theme, config, status, openclaw, scratch, skill }
636
1517
  })
637
1518
 
638
- runMain(main)
1519
+ // Route `moi config --help` to the same terse cheat sheet as `moi config help`;
1520
+ // every other command keeps citty's default usage renderer.
1521
+ runMain(main, {
1522
+ async showUsage(cmd, parent) {
1523
+ const meta = typeof cmd.meta === 'function' ? await cmd.meta() : await cmd.meta
1524
+ if (meta?.name === 'config') {
1525
+ printConfigHelp()
1526
+ return
1527
+ }
1528
+ await showUsage(cmd, parent)
1529
+ }
1530
+ })