moi-computer 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/bunfig.toml +4 -0
  2. package/client/api/workspaces.ts +277 -6
  3. package/client/assets/mcp/agentation.png +0 -0
  4. package/client/assets/mcp/airtable.png +0 -0
  5. package/client/assets/mcp/apollo.png +0 -0
  6. package/client/assets/mcp/asana.png +0 -0
  7. package/client/assets/mcp/box.png +0 -0
  8. package/client/assets/mcp/chrome.svg +33 -0
  9. package/client/assets/mcp/clickup.png +0 -0
  10. package/client/assets/mcp/cloudflare.png +0 -0
  11. package/client/assets/mcp/context7.png +0 -0
  12. package/client/assets/mcp/datadog.png +0 -0
  13. package/client/assets/mcp/dropbox.png +0 -0
  14. package/client/assets/mcp/elevenlabs.png +0 -0
  15. package/client/assets/mcp/exa.png +0 -0
  16. package/client/assets/mcp/firecrawl.png +0 -0
  17. package/client/assets/mcp/gmail.png +0 -0
  18. package/client/assets/mcp/googlecalendar.png +0 -0
  19. package/client/assets/mcp/googledrive.png +0 -0
  20. package/client/assets/mcp/grafana.png +0 -0
  21. package/client/assets/mcp/huggingface.png +0 -0
  22. package/client/assets/mcp/intercom.png +0 -0
  23. package/client/assets/mcp/monday.png +0 -0
  24. package/client/assets/mcp/mongodb.png +0 -0
  25. package/client/assets/mcp/paper.png +0 -0
  26. package/client/assets/mcp/paypal.png +0 -0
  27. package/client/assets/mcp/perplexity.png +0 -0
  28. package/client/assets/mcp/postgresql.png +0 -0
  29. package/client/assets/mcp/posthog.png +0 -0
  30. package/client/assets/mcp/puppeteer.png +0 -0
  31. package/client/assets/mcp/railway.png +0 -0
  32. package/client/assets/mcp/redis.png +0 -0
  33. package/client/assets/mcp/salesforce.png +0 -0
  34. package/client/assets/mcp/shopify.png +0 -0
  35. package/client/assets/mcp/snowflake.png +0 -0
  36. package/client/assets/mcp/telegram.png +0 -0
  37. package/client/assets/mcp/twilio.png +0 -0
  38. package/client/assets/mcp/zapier.png +0 -0
  39. package/client/components/App.tsx +7 -1
  40. package/client/components/ChatInput.tsx +194 -13
  41. package/client/components/ChatPanel.tsx +116 -47
  42. package/client/components/ChatPopup.tsx +1 -1
  43. package/client/components/IconMcp.tsx +21 -0
  44. package/client/components/McpMenu.tsx +125 -0
  45. package/client/components/ModelPicker.tsx +147 -0
  46. package/client/components/Scratchpad.tsx +775 -0
  47. package/client/components/ShimmerText.tsx +20 -0
  48. package/client/components/ThreadSelector.tsx +2 -2
  49. package/client/components/TurnView.tsx +111 -531
  50. package/client/components/WidgetShell.tsx +1 -1
  51. package/client/components/WorkspacesPage.tsx +12 -4
  52. package/client/components/layout/SidebarLayout.tsx +18 -9
  53. package/client/components/playground/ToolCallsPage.tsx +81 -0
  54. package/client/components/routes/workspace/[id].tsx +534 -141
  55. package/client/components/routes/workspace/create.tsx +155 -0
  56. package/client/components/settings/IconPicker.tsx +590 -0
  57. package/client/components/settings/SettingsPages.tsx +307 -0
  58. package/client/components/settings/WorkspaceSettings.tsx +92 -0
  59. package/client/components/tool-group/CodeBlock.tsx +41 -0
  60. package/client/components/tool-group/Collapse.tsx +28 -0
  61. package/client/components/tool-group/ReadImagePreview.tsx +46 -0
  62. package/client/components/tool-group/SubagentCard.tsx +135 -0
  63. package/client/components/tool-group/TimelineRow.tsx +147 -0
  64. package/client/components/tool-group/ToolCallGroup.tsx +231 -0
  65. package/client/components/tool-group/ToolOutput.tsx +139 -0
  66. package/client/components/tool-group/detect.ts +93 -0
  67. package/client/components/tool-group/fixtures.ts +315 -0
  68. package/client/components/tool-group/format.ts +211 -0
  69. package/client/components/tool-group/index.ts +9 -0
  70. package/client/components/ui/dialog.tsx +58 -0
  71. package/client/components/ui/hover-card.tsx +44 -0
  72. package/client/components/ui/switch.tsx +23 -0
  73. package/client/components/ui/tooltip.tsx +54 -0
  74. package/client/externalize-react.ts +6 -0
  75. package/client/hooks/useApplet.ts +117 -0
  76. package/client/hooks/useChat.ts +162 -62
  77. package/client/hooks/useMeiEvents.ts +9 -2
  78. package/client/hooks/useStickToBottom.ts +86 -0
  79. package/client/hooks/useWorkspaceTheme.ts +8 -2
  80. package/client/index.css +48 -2
  81. package/client/index.html +9 -5
  82. package/client/index.tsx +29 -2
  83. package/client/lib/WorkspaceContext.tsx +5 -8
  84. package/client/lib/WorkspaceLayoutContext.tsx +30 -10
  85. package/client/lib/applet-cache.ts +54 -0
  86. package/client/lib/connection.ts +237 -0
  87. package/client/lib/flags.ts +10 -0
  88. package/client/lib/mcp-icons.ts +142 -10
  89. package/client/lib/preview-turn.ts +37 -0
  90. package/client/lib/render-icon.ts +173 -0
  91. package/client/lib/scratch-executor.ts +20 -0
  92. package/client/lib/uploads.ts +18 -0
  93. package/client/main.tsx +5 -0
  94. package/client/store/live.ts +282 -0
  95. package/client/structured-clone-shim.ts +14 -0
  96. package/client/theme.css +2 -2
  97. package/client/vendor/emojibase/en/data.json +1 -0
  98. package/client/vendor/emojibase/en/messages.json +1 -0
  99. package/client/vendor/react/development/_impl/react-dom-client.js +15871 -0
  100. package/client/vendor/react/development/_impl/react-dom.js +223 -0
  101. package/client/vendor/react/development/_impl/react-jsx-dev-runtime.js +256 -0
  102. package/client/vendor/react/development/_impl/react-jsx-runtime.js +260 -0
  103. package/client/vendor/react/development/_impl/react.js +863 -0
  104. package/client/vendor/react/development/react-dom-client.js +6 -0
  105. package/client/vendor/react/development/react-dom.js +17 -0
  106. package/client/vendor/react/development/react-jsx-dev-runtime.js +5 -0
  107. package/client/vendor/react/development/react-jsx-runtime.js +6 -0
  108. package/client/vendor/react/development/react.js +47 -0
  109. package/client/vendor/react/production/_impl/react-dom-client.js +10361 -0
  110. package/client/vendor/react/production/_impl/react-dom.js +184 -0
  111. package/client/vendor/react/production/_impl/react-jsx-dev-runtime.js +37 -0
  112. package/client/vendor/react/production/_impl/react-jsx-runtime.js +60 -0
  113. package/client/vendor/react/production/_impl/react.js +428 -0
  114. package/client/vendor/react/production/react-dom-client.js +6 -0
  115. package/client/vendor/react/production/react-dom.js +17 -0
  116. package/client/vendor/react/production/react-jsx-dev-runtime.js +5 -0
  117. package/client/vendor/react/production/react-jsx-runtime.js +6 -0
  118. package/client/vendor/react/production/react.js +47 -0
  119. package/dist/agentation-4s0nn45p.png +0 -0
  120. package/dist/airtable-hsa66v6q.png +0 -0
  121. package/dist/apollo-2ed5dy2d.png +0 -0
  122. package/dist/asana-tvgtwbx2.png +0 -0
  123. package/dist/box-w3n36t5g.png +0 -0
  124. package/dist/chrome-tspm94rw.svg +33 -0
  125. package/dist/chunk-kc6e9nd4.css +1 -0
  126. package/dist/chunk-yf3p7qg7.js +673 -0
  127. package/dist/clickup-qqrqqvqb.png +0 -0
  128. package/dist/cloudflare-j9p931v6.png +0 -0
  129. package/dist/context7-8ht0xjfy.png +0 -0
  130. package/dist/datadog-70ne3yzt.png +0 -0
  131. package/dist/dropbox-4m5s9mgr.png +0 -0
  132. package/dist/elevenlabs-2nzzej1t.png +0 -0
  133. package/dist/exa-qqj3vr0x.png +0 -0
  134. package/dist/firecrawl-w2t8nehx.png +0 -0
  135. package/dist/gmail-sg6a5v3x.png +0 -0
  136. package/dist/googlecalendar-nqhh2v7r.png +0 -0
  137. package/dist/googledrive-6s8xyab7.png +0 -0
  138. package/dist/grafana-1yfsnwr6.png +0 -0
  139. package/dist/huggingface-kxzaxj83.png +0 -0
  140. package/dist/index.html +10 -6
  141. package/dist/intercom-td763jt8.png +0 -0
  142. package/dist/monday-jdbs4wwf.png +0 -0
  143. package/dist/mongodb-emzxvhd5.png +0 -0
  144. package/dist/paper-zbt34fab.png +0 -0
  145. package/dist/paypal-kwwf7xsc.png +0 -0
  146. package/dist/perplexity-4y63rxvj.png +0 -0
  147. package/dist/postgresql-qsspbsr1.png +0 -0
  148. package/dist/posthog-sphppc4w.png +0 -0
  149. package/dist/puppeteer-2xjt1a9b.png +0 -0
  150. package/dist/railway-834de8d2.png +0 -0
  151. package/dist/redis-spm6w2m1.png +0 -0
  152. package/dist/salesforce-1mk56v4z.png +0 -0
  153. package/dist/shopify-90dadaav.png +0 -0
  154. package/dist/snowflake-hfpykpgy.png +0 -0
  155. package/dist/telegram-v6tjyrs7.png +0 -0
  156. package/dist/twilio-dpyjdwpj.png +0 -0
  157. package/dist/zapier-p67qfch0.png +0 -0
  158. package/lib/attachment-note.ts +48 -0
  159. package/lib/claude-adapter.ts +219 -29
  160. package/lib/format.ts +32 -0
  161. package/lib/types.ts +314 -6
  162. package/package.json +10 -5
  163. package/server/CLAUDE.md +3 -0
  164. package/server/agent.ts +25 -118
  165. package/server/api.ts +593 -0
  166. package/server/applets.ts +396 -0
  167. package/server/build-applet.ts +580 -0
  168. package/server/cc-session.ts +611 -0
  169. package/server/cli-colors.ts +17 -0
  170. package/server/cli-ui.ts +52 -0
  171. package/server/cli.ts +964 -72
  172. package/server/control.ts +166 -19
  173. package/server/debug.ts +10 -0
  174. package/server/events.ts +24 -0
  175. package/server/functions-worker.ts +18 -2
  176. package/server/functions.ts +59 -12
  177. package/server/icon.ts +13 -0
  178. package/server/layout.ts +25 -3
  179. package/server/mcp.ts +125 -0
  180. package/server/moi-scaffold.ts +85 -0
  181. package/server/openclaw-session.ts +41 -10
  182. package/server/openclaw.ts +22 -0
  183. package/server/preview.ts +70 -0
  184. package/server/registry.ts +32 -2
  185. package/server/scratchpad-executor.ts +380 -0
  186. package/server/scratchpad-relay.ts +45 -0
  187. package/server/scratchpad.ts +171 -0
  188. package/server/skill-version.ts +146 -0
  189. package/server/skills-template.ts +6 -1
  190. package/server/state.ts +22 -36
  191. package/server/static.ts +23 -0
  192. package/server/status.ts +94 -0
  193. package/server/thread-config.ts +125 -0
  194. package/server/uploads.ts +0 -0
  195. package/server/vendor.ts +63 -0
  196. package/server/views.ts +0 -0
  197. package/server/web.ts +108 -253
  198. package/server/widgets.ts +52 -142
  199. package/server/workspace-config.ts +37 -0
  200. package/server/workspace-env.ts +407 -0
  201. package/server/workspace-init.ts +66 -0
  202. package/workspace/.claude/skills/moi-workspace/DESIGN.md +109 -0
  203. package/workspace/.claude/skills/moi-workspace/SCRATCHPAD.md +57 -0
  204. package/workspace/.claude/skills/moi-workspace/SKILL.md +252 -0
  205. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +22 -0
  206. package/client/hooks/useWidget.ts +0 -72
  207. package/client/hooks/useWidgetList.ts +0 -30
  208. package/client/lib/ws.ts +0 -129
  209. package/client/store/chat.tsx +0 -162
  210. package/dist/chunk-4615fa69.js +0 -67
  211. package/dist/chunk-582xmy05.css +0 -1
  212. package/server/build-widget.ts +0 -343
  213. package/workspace/.claude/skills/widgets/DESIGN.md +0 -630
  214. package/workspace/.claude/skills/widgets/SKILL.md +0 -176
package/server/control.ts CHANGED
@@ -1,12 +1,50 @@
1
1
  import { resolve } from 'path'
2
2
 
3
+ import type { WorkspaceEntry } from '@/lib/types'
4
+
3
5
  import { CONTROL_PORT } from './constants'
6
+ import { processIcon } from './icon'
4
7
  import { loadLayout, saveLayout } from './layout'
5
- import { listWorkspaces, registerWorkspace } from './registry'
8
+ import { publishEvent } from './events'
9
+ import { findWorkspaceForPath, listWorkspaces, registerWorkspace } from './registry'
10
+ import { executeScratchOp } from './scratchpad-executor'
11
+ import { readScratchpadImage, readScratchpadShapes } from './scratchpad'
12
+ import { relayScratchOp } from './scratchpad-relay'
6
13
  import { broadcastAll } from './state'
7
14
  import { applyThemeUpdate, matchColorTheme } from './theme'
8
- import { publishMei } from './web'
9
15
  import { handleBundle } from './widgets'
16
+ import { handleBundleViews } from './views'
17
+ import { getWorkspaceConfig, setWorkspaceConfig } from './workspace-config'
18
+
19
+ type ControlSocket = { send(data: string): void }
20
+
21
+ // Resolve a control request's `path` to the registered workspace that contains
22
+ // it — the entry itself or its nearest registered ancestor — so every
23
+ // workspace-scoped command (bundle/theme/config/scratch) works from `.moi/` or
24
+ // any subdirectory instead of operating on a phantom nested path. Sends a clear
25
+ // error and returns null when nothing is registered, or the path is outside
26
+ // every workspace.
27
+ async function resolveWorkspace(
28
+ ws: ControlSocket,
29
+ rawPath: unknown
30
+ ): Promise<WorkspaceEntry | null> {
31
+ const workspaces = await listWorkspaces()
32
+ if (workspaces.length === 0) {
33
+ ws.send(JSON.stringify({ error: 'No workspaces registered' }))
34
+ return null
35
+ }
36
+ const reqPath = resolve(String(rawPath ?? workspaces[0].path))
37
+ const match = findWorkspaceForPath(workspaces, reqPath)
38
+ if (!match) {
39
+ ws.send(
40
+ JSON.stringify({
41
+ error: `${reqPath} is not inside a registered moi workspace. Open it in moi, or run from the workspace root.`
42
+ })
43
+ )
44
+ return null
45
+ }
46
+ return match
47
+ }
10
48
 
11
49
  export const control = Bun.serve({
12
50
  port: CONTROL_PORT,
@@ -36,15 +74,33 @@ export const control = Bun.serve({
36
74
  }
37
75
 
38
76
  if (data.type === 'bundle') {
39
- // Bundle needs a workspace path — default to first registered workspace
40
- const workspaces = await listWorkspaces()
41
- if (workspaces.length === 0) {
42
- ws.send(JSON.stringify({ error: 'No workspaces registered' }))
43
- return
77
+ // Resolve to the real workspace root (works from `.moi/` or any
78
+ // subdir; errors when outside every registered workspace) so a bundle
79
+ // never targets a phantom nested `.moi/.moi`.
80
+ const match = await resolveWorkspace(ws, data.path)
81
+ if (!match) return
82
+ const workspacePath = match.path
83
+ const force = !!data.force
84
+ // `only` narrows to one kind; default builds both. Results carry a
85
+ // `kind` so the CLI can label each row.
86
+ const only = data.only === 'widgets' || data.only === 'views' ? data.only : undefined
87
+ const results: {
88
+ kind: 'widget' | 'view'
89
+ name: string
90
+ status: string
91
+ error?: string
92
+ }[] = []
93
+ if (only !== 'views') {
94
+ for (const r of await handleBundle(publishEvent, workspacePath, force)) {
95
+ results.push({ kind: 'widget', name: r.name, status: r.status, error: r.error })
96
+ }
97
+ }
98
+ if (only !== 'widgets') {
99
+ for (const r of await handleBundleViews(publishEvent, workspacePath, force)) {
100
+ results.push({ kind: 'view', name: r.name, status: r.status, error: r.error })
101
+ }
44
102
  }
45
- const workspacePath = String(data.path ?? workspaces[0].path)
46
- const results = await handleBundle(publishMei, workspacePath, !!data.force)
47
- ws.send(JSON.stringify(results))
103
+ ws.send(JSON.stringify({ ok: true, workspacePath, results }))
48
104
  return
49
105
  }
50
106
 
@@ -53,19 +109,16 @@ export const control = Bun.serve({
53
109
  // and re-run its data fetches. No rebuild, no page reload — the
54
110
  // existing `useWidget` hook handles `widgets:refresh` identically
55
111
  // to `widget:updated` (load with bust=true).
56
- publishMei({ type: 'widgets:refresh' })
112
+ publishEvent({ type: 'widgets:refresh' })
57
113
  ws.send(JSON.stringify({ ok: true }))
58
114
  return
59
115
  }
60
116
 
61
117
  if (data.type === 'theme') {
62
- // Theme is per-workspace
63
- const workspaces = await listWorkspaces()
64
- if (workspaces.length === 0) {
65
- ws.send(JSON.stringify({ error: 'No workspaces registered' }))
66
- return
67
- }
68
- const workspacePath = String(data.path ?? workspaces[0].path)
118
+ // Theme is per-workspace — resolve to the real root (subdir-safe).
119
+ const match = await resolveWorkspace(ws, data.path)
120
+ if (!match) return
121
+ const workspacePath = match.path
69
122
  const layout = await loadLayout(workspacePath)
70
123
 
71
124
  // Listing mode — neither axis requested
@@ -86,8 +139,102 @@ export const control = Bun.serve({
86
139
  }
87
140
 
88
141
  await saveLayout({ ...layout, theme: result.theme }, workspacePath)
89
- publishMei({ type: 'theme:updated' })
142
+ publishEvent({ type: 'theme:updated' })
90
143
  ws.send(JSON.stringify({ ok: true, ...result.applied }))
144
+ return
145
+ }
146
+
147
+ if (data.type === 'config') {
148
+ // Workspace identity (name + icon) is per-workspace — subdir-safe.
149
+ const match = await resolveWorkspace(ws, data.path)
150
+ if (!match) return
151
+ const workspacePath = match.path
152
+ const hasName = typeof data.name === 'string'
153
+ const hasIcon = typeof data.iconPath === 'string'
154
+ const clearName = data.clearName === true
155
+ const clearIcon = data.clearIcon === true
156
+
157
+ // Listing mode — no field requested.
158
+ if (!hasName && !hasIcon && !clearName && !clearIcon) {
159
+ const cfg = await getWorkspaceConfig(workspacePath)
160
+ ws.send(
161
+ JSON.stringify({ name: cfg.name ?? null, hasIcon: !!cfg.icon, path: workspacePath })
162
+ )
163
+ return
164
+ }
165
+
166
+ // `null` clears a field; a value sets it; `undefined` leaves it unchanged.
167
+ const patch: { name?: string | null; icon?: string | null } = {}
168
+ if (clearName) patch.name = null
169
+ else if (hasName) patch.name = String(data.name)
170
+ if (clearIcon) patch.icon = null
171
+ else if (hasIcon) {
172
+ try {
173
+ patch.icon = await processIcon(String(data.iconPath))
174
+ } catch (err) {
175
+ const msg = err instanceof Error ? err.message : String(err)
176
+ ws.send(JSON.stringify({ error: `Could not read image: ${msg}` }))
177
+ return
178
+ }
179
+ }
180
+
181
+ await setWorkspaceConfig(workspacePath, patch)
182
+ publishEvent({ type: 'workspace:updated' })
183
+ ws.send(
184
+ JSON.stringify({
185
+ ok: true,
186
+ name: patch.name ?? null,
187
+ icon: hasIcon,
188
+ clearedName: clearName,
189
+ clearedIcon: clearIcon
190
+ })
191
+ )
192
+ return
193
+ }
194
+
195
+ if (data.type === 'scratch') {
196
+ const op = data.op
197
+ if (!op || typeof op.kind !== 'string') {
198
+ ws.send(JSON.stringify({ error: 'Missing scratch op' }))
199
+ return
200
+ }
201
+ // Resolve to the real workspace root (subdir-safe) — both the on-disk
202
+ // read and the live relay use it.
203
+ const match = await resolveWorkspace(ws, data.path)
204
+ if (!match) return
205
+
206
+ // `read` is served straight off the disk snapshot — no live tab needed.
207
+ if (op.kind === 'read') {
208
+ ws.send(JSON.stringify({ shapes: await readScratchpadShapes(match.path) }))
209
+ return
210
+ }
211
+
212
+ // `read-image` resolves one image shape's data off disk too — `read`
213
+ // omits the blob, so this is how the agent pulls a specific image.
214
+ if (op.kind === 'read-image') {
215
+ ws.send(JSON.stringify(await readScratchpadImage(match.path, String(op.name))))
216
+ return
217
+ }
218
+
219
+ // Assign add ops a stable name when the caller didn't (`--id`), so the
220
+ // derived tldraw shape id is deterministic and addressable later.
221
+ if (op.kind.startsWith('add-') && !op.name) {
222
+ op.name = `s_${crypto.randomUUID().slice(0, 8)}`
223
+ }
224
+
225
+ try {
226
+ // `view` renders pixels — only the browser can do that, so it relays to
227
+ // a live tab (and fails if none is open). Every mutation runs headlessly
228
+ // against the disk snapshot, so drawing never needs an open canvas.
229
+ const result =
230
+ op.kind === 'view'
231
+ ? await relayScratchOp(match.id, op)
232
+ : await executeScratchOp(match.path, match.id, op)
233
+ ws.send(JSON.stringify({ ok: true, result }))
234
+ } catch (err) {
235
+ ws.send(JSON.stringify({ error: err instanceof Error ? err.message : String(err) }))
236
+ }
237
+ return
91
238
  }
92
239
  } catch (err) {
93
240
  console.error('[control]', err)
@@ -0,0 +1,10 @@
1
+ // Opt-in messaging trace for the chat/session pipeline. Enabled by
2
+ // `moi start --debug` (which sets MOI_DEBUG=1 on the server child). Intentionally
3
+ // undocumented — a quick console peek for when a turn appears to hang (loader
4
+ // spins forever): you can watch the message land, the session create/resume, the
5
+ // turn start, and the `result` that should clear the spinner. No-op unless set.
6
+ export const debugEnabled = !!process.env.MOI_DEBUG
7
+
8
+ export function debug(...args: unknown[]): void {
9
+ if (debugEnabled) console.log('\x1b[2m[debug]\x1b[0m', ...args)
10
+ }
@@ -0,0 +1,24 @@
1
+ // Live-event channel: server → browser push over the `/api/workspaces/ws`
2
+ // socket. Bundles, the control server, and the REST API publish build/refresh/
3
+ // identity events (`widgets:refresh`, `theme:updated`, `workspace:updated`, …)
4
+ // here; every subscribed browser receives them. This is not a transport of its
5
+ // own — it rides the Bun WebSocket pub/sub already open for that route.
6
+ //
7
+ // The publisher is the Bun.serve instance created in web.ts, wired in via
8
+ // `setEventServer` once it exists. Keeping `publishEvent` in its own module lets
9
+ // web.ts, control.ts, and the Hono API all publish without forming an import
10
+ // cycle through web.ts (which binds ports on load).
11
+
12
+ export const EVENTS_TOPIC = 'events'
13
+
14
+ type EventPublisher = { publish: (topic: string, data: string) => unknown }
15
+
16
+ let publisher: EventPublisher | null = null
17
+
18
+ export function setEventServer(server: EventPublisher) {
19
+ publisher = server
20
+ }
21
+
22
+ export function publishEvent(msg: unknown) {
23
+ publisher?.publish(EVENTS_TOPIC, JSON.stringify(msg))
24
+ }
@@ -1,10 +1,20 @@
1
1
  // MEI Functions Worker — child process that loads and executes .server.ts modules.
2
2
  // Spawned by the main process with IPC. Receives call/reload messages.
3
3
  import { parse, stringify } from 'devalue'
4
- import { join } from 'path'
4
+ import { join, resolve, sep } from 'path'
5
5
 
6
6
  const MEI_DIR =
7
- process.env.MEI_FUNCTIONS_DIR ?? join(import.meta.dir, '..', 'test-workspace', '.widgets')
7
+ process.env.MEI_FUNCTIONS_DIR ?? join(import.meta.dir, '..', 'test-workspace', '.moi')
8
+
9
+ // The parent spawns us from a neutral cwd so Bun never auto-loads the
10
+ // workspace's `.env` into this process — moi injects the resolved, scope-filtered
11
+ // env at spawn instead (see functions.ts). Restore the documented
12
+ // `cwd = workspace root` so server functions can use plain relative paths.
13
+ if (process.env.MEI_WORKSPACE_ROOT) {
14
+ try {
15
+ process.chdir(process.env.MEI_WORKSPACE_ROOT)
16
+ } catch {}
17
+ }
8
18
 
9
19
  const moduleCache = new Map<string, Record<string, unknown>>()
10
20
 
@@ -20,7 +30,13 @@ async function loadModule(name: string): Promise<Record<string, unknown>> {
20
30
  const cached = moduleCache.get(name)
21
31
  if (cached) return cached
22
32
 
33
+ // Module keys are paths relative to MEI_DIR (the workspace's `.moi/`),
34
+ // e.g. "widgets/hello". Defense-in-depth: the route already rejects `..`
35
+ // segments, but never load a file that resolves outside MEI_DIR.
23
36
  const filePath = join(MEI_DIR, `${name}.server.ts`)
37
+ if (!resolve(filePath).startsWith(resolve(MEI_DIR) + sep)) {
38
+ throw new Error(`Server module "${name}" not found`)
39
+ }
24
40
  const file = Bun.file(filePath)
25
41
 
26
42
  if (!(await file.exists())) {
@@ -8,12 +8,19 @@
8
8
  // against multiple workspaces stay isolated.
9
9
  //
10
10
  // CWD contract: workers run with `cwd = workspacePath` (the workspace root,
11
- // where the agent works), NOT `.widgets/`. The `.widgets/` location is
12
- // passed to the worker as `MEI_FUNCTIONS_DIR` so it can locate `.server.ts`
13
- // files. This is the contract documented in the widgets SKILL.
11
+ // where the agent works), NOT `.moi/`. But we SPAWN from a neutral cwd and have
12
+ // the worker `chdir` there at startup (via MEI_WORKSPACE_ROOT) — otherwise Bun
13
+ // would auto-load the workspace's `.env` into the worker, bypassing moi's
14
+ // inheritDotenv toggle and per-sink scoping. The `.moi/` root is passed as
15
+ // `MEI_FUNCTIONS_DIR` so the worker can locate `.server.ts` files — module keys
16
+ // are paths relative to it (`"widgets/hello"` → `.moi/widgets/hello.server.ts`).
17
+ // This is the contract documented in the widgets SKILL.
14
18
  import { LRUCache } from 'lru-cache'
19
+ import { tmpdir } from 'node:os'
15
20
  import { join } from 'path'
16
21
 
22
+ import { resolveWorkspaceEnv } from './workspace-env'
23
+
17
24
  const WORKER_PATH = join(import.meta.dir, 'functions-worker.ts')
18
25
  const CALL_TIMEOUT_MS = 30_000
19
26
  const WORKER_IDLE_TTL_MS = 10 * 60_000
@@ -58,8 +65,8 @@ const slots = new LRUCache<string, Slot>({
58
65
  dispose: slot => killSlot(slot, 'Functions worker idle-evicted')
59
66
  })
60
67
 
61
- function spawnSlot(workspacePath: string): Slot {
62
- const meiDir = join(workspacePath, '.widgets')
68
+ function spawnSlot(workspacePath: string, workspaceEnv: Record<string, string>): Slot {
69
+ const meiDir = join(workspacePath, '.moi')
63
70
 
64
71
  let readyResolve: () => void = () => {}
65
72
  const readyPromise = new Promise<void>(r => (readyResolve = r))
@@ -73,10 +80,20 @@ function spawnSlot(workspacePath: string): Slot {
73
80
  }
74
81
 
75
82
  slot.worker = Bun.spawn([process.execPath, WORKER_PATH], {
76
- cwd: workspacePath,
77
- // Default to the workspace's built functions dir, but let an explicitly-set
78
- // MEI_FUNCTIONS_DIR win (used by tests to point the worker at fixtures).
79
- env: { ...process.env, MEI_FUNCTIONS_DIR: process.env.MEI_FUNCTIONS_DIR ?? meiDir },
83
+ // Neutral cwd so Bun doesn't auto-load the workspace's `.env`; the worker
84
+ // chdir()s to MEI_WORKSPACE_ROOT at startup to restore cwd = workspace root.
85
+ cwd: tmpdir(),
86
+ // Resolved workspace env (.env + scope-filtered custom secrets) layered over
87
+ // the server's env — the AUTHORITATIVE source now that auto-load is off, so
88
+ // inheritDotenv and per-sink scoping actually hold. MEI_FUNCTIONS_DIR is
89
+ // applied last so a workspace .env can never clobber it; tests set it
90
+ // explicitly to point the worker at fixtures.
91
+ env: {
92
+ ...process.env,
93
+ ...workspaceEnv,
94
+ MEI_WORKSPACE_ROOT: workspacePath,
95
+ MEI_FUNCTIONS_DIR: process.env.MEI_FUNCTIONS_DIR ?? meiDir
96
+ },
80
97
  stderr: 'inherit',
81
98
  onExit(_proc, code) {
82
99
  if (code !== 0 && code !== null) {
@@ -114,22 +131,42 @@ function spawnSlot(workspacePath: string): Slot {
114
131
  return slot
115
132
  }
116
133
 
117
- function getOrSpawn(workspacePath: string): Slot {
134
+ function getOrSpawn(workspacePath: string, workspaceEnv: Record<string, string>): Slot {
118
135
  const existing = slots.get(workspacePath)
119
136
  if (existing && !existing.killed) return existing
120
137
 
121
- const fresh = spawnSlot(workspacePath)
138
+ const fresh = spawnSlot(workspacePath, workspaceEnv)
122
139
  slots.set(workspacePath, fresh)
123
140
  return fresh
124
141
  }
125
142
 
143
+ // Parse the `<module>/<fn>` tail of an RPC URL. The module key may itself
144
+ // contain slashes (`widgets/hello/getWeather` → module `widgets/hello`, fn
145
+ // `getWeather`), so split on the LAST slash. Returns null on anything that
146
+ // isn't a clean path: empty or `..`-ish segments, leading/trailing slashes,
147
+ // characters outside [A-Za-z0-9_$-].
148
+ export function parseFunctionPath(tail: string): { module: string; name: string } | null {
149
+ const i = tail.lastIndexOf('/')
150
+ if (i === -1) return null
151
+ const module = tail.slice(0, i)
152
+ const name = tail.slice(i + 1)
153
+ if (!/^[A-Za-z0-9_$-]+(?:\/[A-Za-z0-9_$-]+)*$/.test(module)) return null
154
+ if (!/^[A-Za-z0-9_$]+$/.test(name)) return null
155
+ return { module, name }
156
+ }
157
+
126
158
  export async function callFunction(
127
159
  module: string,
128
160
  name: string,
129
161
  args: string,
130
162
  workspacePath: string
131
163
  ): Promise<string> {
132
- const slot = getOrSpawn(workspacePath)
164
+ // Resolve the workspace env before (maybe) spawning, so a fresh worker picks
165
+ // up current .env + custom overrides. Env is fixed at spawn — an already-warm
166
+ // worker keeps its snapshot until restartWorker() reaps it. Widgets only see
167
+ // secrets scoped to the 'widgets' sink.
168
+ const workspaceEnv = await resolveWorkspaceEnv(workspacePath, 'widgets')
169
+ const slot = getOrSpawn(workspacePath, workspaceEnv)
133
170
  await slot.readyPromise
134
171
 
135
172
  const id = crypto.randomUUID()
@@ -159,6 +196,16 @@ export function killAllWorkers() {
159
196
  slots.clear()
160
197
  }
161
198
 
199
+ // Reap a workspace's worker so the next callFunction spawns a fresh one with
200
+ // up-to-date env. A running process can't pick up new env vars, so an env
201
+ // change (UI override or .env edit) requires this hard restart — distinct from
202
+ // reloadModules, which only swaps module code inside the live worker.
203
+ export function restartWorker(workspacePath: string) {
204
+ const slot = slots.peek(workspacePath)
205
+ if (slot) killSlot(slot, 'Workspace env changed')
206
+ slots.delete(workspacePath)
207
+ }
208
+
162
209
  export function reloadModules(modules: string[], workspacePath: string) {
163
210
  if (modules.length === 0) return
164
211
  // peek: don't refresh TTL just because files changed. If the worker was
package/server/icon.ts ADDED
@@ -0,0 +1,13 @@
1
+ import sharp from 'sharp'
2
+
3
+ // Normalize any image (PNG/JPG/WebP and animated GIF) into a 128×128
4
+ // transparent WebP, returned as a base64 data URL for inlining in the workspace
5
+ // config. `animated: true` keeps every frame of a GIF; static images are read
6
+ // as a single frame. `fit: 'contain'` preserves aspect with transparent padding.
7
+ export async function processIcon(input: string | Buffer | Uint8Array): Promise<string> {
8
+ const webp = await sharp(input, { animated: true })
9
+ .resize(128, 128, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
10
+ .webp({ quality: 90 })
11
+ .toBuffer()
12
+ return `data:image/webp;base64,${webp.toString('base64')}`
13
+ }
package/server/layout.ts CHANGED
@@ -14,7 +14,7 @@ const PREVIEW_COLS = 4
14
14
  const EMPTY_PREVIEW: WorkspacePreview = { cols: PREVIEW_COLS, items: [] }
15
15
 
16
16
  export function getLayoutPath(workspacePath: string): string {
17
- return join(workspacePath, '.widgets', '.workspace.json')
17
+ return join(workspacePath, '.moi', '.workspace.json')
18
18
  }
19
19
 
20
20
  export async function loadLayout(workspacePath: string): Promise<WorkspaceLayout> {
@@ -30,9 +30,31 @@ export async function saveLayout(layout: WorkspaceLayout, workspacePath: string)
30
30
  await Bun.write(getLayoutPath(workspacePath), JSON.stringify(layout, null, 2))
31
31
  }
32
32
 
33
+ // Merge a client-submitted layout over the stored one for persistence.
34
+ //
35
+ // Everything (grid, chat mode, theme, AND identity) shares one `.workspace.json`,
36
+ // but the grid editor and `moi config` own different fields. The client's layout
37
+ // PUT is authoritative for the editor fields (widgetGrid, chatMode, theme,
38
+ // selectedModel) — but it strips `name` and round-trips a possibly-stale `icon`.
39
+ // A blind overwrite therefore erases a `moi config`-set name (and could revert an
40
+ // icon). So drop whatever identity the body carries and re-apply the server-owned
41
+ // `name`/`icon` from `existing` — conditionally, so an absent field never
42
+ // serializes as `name: undefined`.
43
+ export function mergeLayoutForSave(
44
+ existing: WorkspaceLayout,
45
+ body: WorkspaceLayout
46
+ ): WorkspaceLayout {
47
+ const { name: _name, icon: _icon, ...editor } = body
48
+ return {
49
+ ...editor,
50
+ ...(existing.name !== undefined && { name: existing.name }),
51
+ ...(existing.icon !== undefined && { icon: existing.icon })
52
+ }
53
+ }
54
+
33
55
  async function scanWidgetIds(workspacePath: string): Promise<Set<string>> {
34
56
  try {
35
- const entries = await readdir(join(workspacePath, '.widgets'))
57
+ const entries = await readdir(join(workspacePath, '.moi', 'widgets'))
36
58
  return new Set(
37
59
  entries
38
60
  .filter(f => /\.(tsx|ts)$/.test(f) && !f.endsWith('.server.ts'))
@@ -53,7 +75,7 @@ export async function getWorkspacePreview(workspacePath: string): Promise<Worksp
53
75
 
54
76
  let manifest: Record<string, WidgetConfig> = {}
55
77
  try {
56
- const manifestPath = join(workspacePath, '.widgets', '.build', 'widgets', 'manifest.json')
78
+ const manifestPath = join(workspacePath, '.moi', '.build', 'widgets', 'manifest.json')
57
79
  const parsed = JSON.parse(await Bun.file(manifestPath).text())
58
80
  if (parsed && typeof parsed.config === 'object' && parsed.config !== null) {
59
81
  manifest = parsed.config as Record<string, WidgetConfig>
package/server/mcp.ts ADDED
@@ -0,0 +1,125 @@
1
+ import { query } from '@anthropic-ai/claude-agent-sdk'
2
+ import type { McpServerStatus, SDKUserMessage } from '@anthropic-ai/claude-agent-sdk'
3
+
4
+ import { debugEnabled } from './debug'
5
+
6
+ // MCP server status probing. Intentionally decoupled from agent chat runs
7
+ // (cc-session.ts): connecting to MCP servers and reading their status is a
8
+ // metadata concern, not part of any conversation. Nothing here submits a user
9
+ // turn, so probing costs zero model tokens.
10
+ //
11
+ // Why a streaming-input session that yields nothing: MCP servers (especially
12
+ // remote http / claudeai-proxy ones) connect lazily and asynchronously *after*
13
+ // session init. A single-shot `prompt: ''` query tears down before those
14
+ // handshakes finish, so every server freezes at `pending`. Keeping the session
15
+ // open lets the SDK subprocess finish connecting, and we poll the control-
16
+ // channel `mcpServerStatus()` until nothing is `pending` (or we time out).
17
+
18
+ // The SDK's own MCP connection timeout is 60s; cap our wait to match.
19
+ const SETTLE_TIMEOUT_MS = 60_000
20
+ const POLL_INTERVAL_MS = 750
21
+
22
+ // A status is settled once it leaves `pending` — every other value is terminal
23
+ // for this probe (`connected` / `disabled`, or recoverable `failed` /
24
+ // `needs-auth` that only changes on external action, not by waiting).
25
+ function isSettled(status: McpServerStatus[]): boolean {
26
+ return status.every(s => s.status !== 'pending')
27
+ }
28
+
29
+ // Log the probe result without drowning the console. By default we print a
30
+ // one-line summary — a count of healthy servers plus only the ones that need
31
+ // attention (failed / needs-auth / still-pending) called out by name. The full
32
+ // per-server dump (every `connected` line too) is opt-in via `moi start --debug`.
33
+ // `connected`/`disabled` are the boring majority, so they're folded into counts.
34
+ function logMcpStatus(status: McpServerStatus[]): void {
35
+ if (debugEnabled) {
36
+ console.log('[mcp]', status.map(s => `${s.name}:${s.status}`).join(', '))
37
+ return
38
+ }
39
+ const connected = status.filter(s => s.status === 'connected').length
40
+ const disabled = status.filter(s => s.status === 'disabled').length
41
+ const attention = status.filter(s => s.status !== 'connected' && s.status !== 'disabled')
42
+ const parts = [`${connected} connected`]
43
+ if (disabled) parts.push(`${disabled} disabled`)
44
+ for (const s of attention) parts.push(`${s.status}: ${s.name}`)
45
+ console.log('[mcp]', parts.join(' · '))
46
+ }
47
+
48
+ async function probeMcpStatus(workspacePath: string): Promise<McpServerStatus[]> {
49
+ // A prompt that never yields keeps the session alive without a model turn.
50
+ let release!: () => void
51
+ const done = new Promise<void>(r => (release = r))
52
+ // Never yields by design: yielding would submit a user turn (a model call).
53
+ // We only want the session to stay open while MCP servers connect.
54
+ // eslint-disable-next-line require-yield
55
+ async function* keepAlive(): AsyncGenerator<SDKUserMessage> {
56
+ await done
57
+ }
58
+
59
+ const q = query({
60
+ prompt: keepAlive(),
61
+ options: {
62
+ cwd: workspacePath,
63
+ persistSession: false,
64
+ settingSources: ['user', 'project'],
65
+ env: { ...process.env, CLAUDECODE: undefined }
66
+ }
67
+ })
68
+
69
+ try {
70
+ const start = Date.now()
71
+ let status: McpServerStatus[] = []
72
+ while (Date.now() - start < SETTLE_TIMEOUT_MS) {
73
+ status = await q.mcpServerStatus()
74
+ if (isSettled(status)) break
75
+ await new Promise(r => setTimeout(r, POLL_INTERVAL_MS))
76
+ }
77
+ logMcpStatus(status)
78
+ return status
79
+ } finally {
80
+ release()
81
+ await q.close()
82
+ }
83
+ }
84
+
85
+ // Cache holds a *settled* snapshot for a bounded, content-dependent time — never
86
+ // a cold/pending result, never forever. TTL by volatility: a healthy server
87
+ // stays put, but `failed`/`needs-auth` can recover on external action, so we
88
+ // re-probe those sooner. A still-`pending` snapshot (we hit the timeout) is not
89
+ // cached at all.
90
+ const HEALTHY_TTL_MS = 5 * 60_000
91
+ const RECOVERABLE_TTL_MS = 30_000
92
+
93
+ function ttlFor(status: McpServerStatus[]): number {
94
+ if (status.some(s => s.status === 'pending')) return 0
95
+ if (status.some(s => s.status === 'failed' || s.status === 'needs-auth')) {
96
+ return RECOVERABLE_TTL_MS
97
+ }
98
+ return HEALTHY_TTL_MS
99
+ }
100
+
101
+ type CacheEntry = { status: McpServerStatus[]; expiresAt: number }
102
+ const cache = new Map<string, CacheEntry>()
103
+ // Collapse concurrent callers onto a single in-flight probe (it takes a few
104
+ // seconds to settle). Client-side caching makes stampedes unlikely, but this is
105
+ // cheap insurance against parallel probes of the same workspace.
106
+ const inflight = new Map<string, Promise<McpServerStatus[]>>()
107
+
108
+ export async function getMcpStatus(workspacePath: string): Promise<McpServerStatus[]> {
109
+ const cached = cache.get(workspacePath)
110
+ if (cached && cached.expiresAt > Date.now()) return cached.status
111
+
112
+ const existing = inflight.get(workspacePath)
113
+ if (existing) return existing
114
+
115
+ const probe = probeMcpStatus(workspacePath)
116
+ .then(status => {
117
+ const ttl = ttlFor(status)
118
+ if (ttl > 0) cache.set(workspacePath, { status, expiresAt: Date.now() + ttl })
119
+ return status
120
+ })
121
+ .finally(() => inflight.delete(workspacePath))
122
+
123
+ inflight.set(workspacePath, probe)
124
+ return probe
125
+ }