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
@@ -0,0 +1,407 @@
1
+ // Per-workspace environment variables surfaced to both spawn sites: the widget
2
+ // function workers (functions.ts) and the agent chat session (cc-session.ts).
3
+ //
4
+ // Two sources feed a workspace's effective env:
5
+ // 1. Discovered `.env` files in the workspace root (`.env`, then `.env.local`,
6
+ // local winning). Parsed with node:util's built-in `parseEnv` — no dep.
7
+ // `.env` flows to BOTH sinks (it's the workspace's own file).
8
+ // 2. UI-managed custom secrets. These never touch the repo. Secret VALUES are
9
+ // stored via the OS keychain (`Bun.secrets`) when available, else a 0600
10
+ // file fallback — see SecretStore. Each custom key has a sink scope
11
+ // (widgets / agent / both) so a secret can be kept out of the agent's
12
+ // bypass-permissions Bash. Custom wins over `.env`.
13
+ //
14
+ // Non-secret metadata (the `inheritDotenv` mode flag + per-key scopes, which
15
+ // double as the key-name list for the UI) lives in a small JSON file in the OS
16
+ // data dir. Secret values live in the SecretStore. The two are keyed by the
17
+ // absolute workspace path.
18
+ import envPaths from 'env-paths'
19
+ import { chmod, mkdir, rename } from 'node:fs/promises'
20
+ import { dirname, join, resolve } from 'node:path'
21
+ import { parseEnv } from 'node:util'
22
+
23
+ import type { EnvScope, WorkspaceEnvView } from '@/lib/types'
24
+
25
+ // Dotenv files scanned in the workspace root, low → high precedence. A later
26
+ // file's keys override an earlier file's (base `.env`, machine-local `.env.local`).
27
+ const DOTENV_FILES = ['.env', '.env.local'] as const
28
+
29
+ // Valid POSIX-ish env var name. Used to reject junk keys from the API.
30
+ const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/
31
+ const SCOPES: readonly EnvScope[] = ['widgets', 'agent', 'both']
32
+
33
+ export function isValidEnvKey(key: string): boolean {
34
+ return ENV_KEY_RE.test(key)
35
+ }
36
+
37
+ export function isValidScope(scope: unknown): scope is EnvScope {
38
+ return typeof scope === 'string' && (SCOPES as readonly string[]).includes(scope)
39
+ }
40
+
41
+ // Where a key may flow, given its sink. `agent`/`widgets` only match their own
42
+ // sink; `both` matches either.
43
+ type Sink = 'widgets' | 'agent'
44
+
45
+ const DATA_DIR = envPaths('moi', { suffix: false }).data
46
+ const DEFAULT_META_PATH = join(DATA_DIR, 'workspace-env.json')
47
+ const DEFAULT_SECRET_PATH = join(DATA_DIR, 'workspace-secrets.json')
48
+ // Keychain namespace for Bun.secrets entries.
49
+ const SECRET_SERVICE = 'com.molefrog.moi'
50
+
51
+ // ---------------------------------------------------------------------------
52
+ // JSON helpers
53
+ // ---------------------------------------------------------------------------
54
+
55
+ // Parse a JSON object, returning {} on any failure (missing/empty/malformed).
56
+ function parseJsonObject<T extends object>(text: string | null): T {
57
+ if (!text) return {} as T
58
+ try {
59
+ const parsed = JSON.parse(text)
60
+ return parsed && typeof parsed === 'object' ? (parsed as T) : ({} as T)
61
+ } catch {
62
+ return {} as T
63
+ }
64
+ }
65
+
66
+ async function readJsonObjectFile<T extends object>(path: string): Promise<T> {
67
+ try {
68
+ return parseJsonObject<T>(await Bun.file(path).text())
69
+ } catch {
70
+ return {} as T
71
+ }
72
+ }
73
+
74
+ // Atomic, owner-only write: temp-then-rename so a crash or concurrent write
75
+ // can't truncate the store; 0600 file in a 0700 dir.
76
+ async function writeJsonAtomic(path: string, data: unknown): Promise<void> {
77
+ const dir = dirname(path)
78
+ await mkdir(dir, { recursive: true })
79
+ try {
80
+ await chmod(dir, 0o700)
81
+ } catch {}
82
+ const tmp = `${path}.${process.pid}.tmp`
83
+ await Bun.write(tmp, JSON.stringify(data, null, 2))
84
+ await chmod(tmp, 0o600)
85
+ await rename(tmp, path)
86
+ }
87
+
88
+ // ---------------------------------------------------------------------------
89
+ // Paths + per-workspace write serialization (overridable for tests)
90
+ // ---------------------------------------------------------------------------
91
+
92
+ let _metaPath = DEFAULT_META_PATH
93
+ let _secretFilePath = DEFAULT_SECRET_PATH
94
+
95
+ export function setWorkspaceEnvStorePath(metaPath: string, secretPath?: string) {
96
+ _metaPath = metaPath
97
+ if (secretPath) _secretFilePath = secretPath
98
+ _storePromise = null
99
+ }
100
+
101
+ // Reset module globals to defaults. Tests call this so path/backend overrides
102
+ // don't leak across files.
103
+ export function resetWorkspaceEnvForTest() {
104
+ _metaPath = DEFAULT_META_PATH
105
+ _secretFilePath = DEFAULT_SECRET_PATH
106
+ setSecretStoreBackend('auto')
107
+ }
108
+
109
+ // Serialize writes per workspace path so two concurrent PUTs can't lose an
110
+ // update — `updateWorkspaceEnv` is a read-modify-write over two files, and the
111
+ // atomic write only prevents torn files, not lost updates.
112
+ const _writeChains = new Map<string, Promise<unknown>>()
113
+
114
+ function withWriteLock<T>(key: string, fn: () => Promise<T>): Promise<T> {
115
+ const prev = _writeChains.get(key) ?? Promise.resolve()
116
+ const run = prev.then(fn, fn)
117
+ // Swallow rejections on the chain tail so one failed write doesn't poison the
118
+ // next; callers still see their own promise's rejection via `run`.
119
+ _writeChains.set(
120
+ key,
121
+ run.catch(() => {})
122
+ )
123
+ return run
124
+ }
125
+
126
+ // ---------------------------------------------------------------------------
127
+ // SecretStore: where custom secret VALUES live
128
+ // ---------------------------------------------------------------------------
129
+
130
+ // Per-workspace bag of `{ KEY: value }`. Stored as one opaque value per
131
+ // workspace (keychain entry or file row). Values never leave this layer except
132
+ // when injected into a spawn.
133
+ type SecretStore = {
134
+ readonly backend: 'keychain' | 'file'
135
+ get(workspacePath: string): Promise<Record<string, string>>
136
+ set(workspacePath: string, secrets: Record<string, string>): Promise<void>
137
+ }
138
+
139
+ // Primary: OS-native secure storage via Bun.secrets (Keychain / libsecret /
140
+ // Credential Manager). Encrypted at rest, user-scoped, no password prompt.
141
+ class KeychainSecretStore implements SecretStore {
142
+ readonly backend = 'keychain' as const
143
+
144
+ async get(workspacePath: string): Promise<Record<string, string>> {
145
+ const raw = await Bun.secrets.get({ service: SECRET_SERVICE, name: resolve(workspacePath) })
146
+ return parseJsonObject<Record<string, string>>(raw)
147
+ }
148
+
149
+ async set(workspacePath: string, secrets: Record<string, string>): Promise<void> {
150
+ const name = resolve(workspacePath)
151
+ if (Object.keys(secrets).length === 0) {
152
+ try {
153
+ await Bun.secrets.delete({ service: SECRET_SERVICE, name })
154
+ } catch {}
155
+ return
156
+ }
157
+ await Bun.secrets.set({ service: SECRET_SERVICE, name, value: JSON.stringify(secrets) })
158
+ }
159
+ }
160
+
161
+ // Fallback for hosts without a keyring (headless Linux, CI, SSH). Plaintext
162
+ // JSON, but written 0600 in a 0700 dir and atomically. No encryption at rest —
163
+ // a local keyfile would have the same exposure as the data, so it adds nothing.
164
+ class FileSecretStore implements SecretStore {
165
+ readonly backend = 'file' as const
166
+
167
+ private readAll(): Promise<Record<string, Record<string, string>>> {
168
+ return readJsonObjectFile<Record<string, Record<string, string>>>(_secretFilePath)
169
+ }
170
+
171
+ async get(workspacePath: string): Promise<Record<string, string>> {
172
+ return (await this.readAll())[resolve(workspacePath)] ?? {}
173
+ }
174
+
175
+ async set(workspacePath: string, secrets: Record<string, string>): Promise<void> {
176
+ const all = await this.readAll()
177
+ const key = resolve(workspacePath)
178
+ if (Object.keys(secrets).length === 0) delete all[key]
179
+ else all[key] = secrets
180
+ await writeJsonAtomic(_secretFilePath, all)
181
+ }
182
+ }
183
+
184
+ // Non-mutating probe: a `get` of a missing key returns null when the keyring
185
+ // works, throws when it's unavailable. Avoids polluting the keychain.
186
+ async function keychainAvailable(): Promise<boolean> {
187
+ try {
188
+ await Bun.secrets.get({ service: SECRET_SERVICE, name: '__moi_probe__' })
189
+ return true
190
+ } catch {
191
+ return false
192
+ }
193
+ }
194
+
195
+ let _backend: 'auto' | 'file' | 'keychain' = 'auto'
196
+ let _storePromise: Promise<SecretStore> | null = null
197
+
198
+ // Force a backend (tests pin 'file' so they never touch the real keychain).
199
+ export function setSecretStoreBackend(backend: 'auto' | 'file' | 'keychain') {
200
+ _backend = backend
201
+ _storePromise = null
202
+ }
203
+
204
+ async function createSecretStore(): Promise<SecretStore> {
205
+ if (_backend === 'file') return new FileSecretStore()
206
+ if (_backend === 'keychain') return new KeychainSecretStore()
207
+ if (await keychainAvailable()) {
208
+ console.log('[env] workspace secrets: OS keychain')
209
+ return new KeychainSecretStore()
210
+ }
211
+ console.warn(
212
+ `[env] OS keychain unavailable — storing workspace secrets in ${_secretFilePath} (0600).`
213
+ )
214
+ return new FileSecretStore()
215
+ }
216
+
217
+ function secretStore(): Promise<SecretStore> {
218
+ if (!_storePromise) _storePromise = createSecretStore()
219
+ return _storePromise
220
+ }
221
+
222
+ // ---------------------------------------------------------------------------
223
+ // Metadata: inheritDotenv + per-key scopes (NOT secret)
224
+ // ---------------------------------------------------------------------------
225
+
226
+ type EnvMeta = { inheritDotenv: boolean; scopes: Record<string, EnvScope> }
227
+ type MetaStore = Record<string, EnvMeta>
228
+
229
+ async function getMeta(workspacePath: string): Promise<EnvMeta> {
230
+ const e = (await readJsonObjectFile<MetaStore>(_metaPath))[resolve(workspacePath)]
231
+ if (!e || typeof e !== 'object') return { inheritDotenv: true, scopes: {} }
232
+ return {
233
+ inheritDotenv: e.inheritDotenv !== false,
234
+ scopes: e.scopes && typeof e.scopes === 'object' ? e.scopes : {}
235
+ }
236
+ }
237
+
238
+ async function writeMeta(workspacePath: string, meta: EnvMeta): Promise<void> {
239
+ const store = await readJsonObjectFile<MetaStore>(_metaPath)
240
+ store[resolve(workspacePath)] = meta
241
+ await writeJsonAtomic(_metaPath, store)
242
+ }
243
+
244
+ // The scope of a custom key, defaulting to 'both' when unset.
245
+ function scopeOf(meta: EnvMeta, key: string): EnvScope {
246
+ return meta.scopes[key] ?? 'both'
247
+ }
248
+
249
+ // ---------------------------------------------------------------------------
250
+ // Dotenv discovery
251
+ // ---------------------------------------------------------------------------
252
+
253
+ type DotenvFile = { file: string; vars: Record<string, string> }
254
+
255
+ async function discoverDotenv(workspacePath: string): Promise<DotenvFile[]> {
256
+ const out: DotenvFile[] = []
257
+ for (const file of DOTENV_FILES) {
258
+ const f = Bun.file(resolve(workspacePath, file))
259
+ if (!(await f.exists())) continue
260
+ try {
261
+ out.push({ file, vars: parseEnv(await f.text()) as Record<string, string> })
262
+ } catch {
263
+ // A malformed .env shouldn't take the whole resolve down.
264
+ }
265
+ }
266
+ return out
267
+ }
268
+
269
+ function mergeDotenv(files: DotenvFile[]): Record<string, string> {
270
+ const merged: Record<string, string> = {}
271
+ for (const { vars } of files) Object.assign(merged, vars)
272
+ return merged
273
+ }
274
+
275
+ // Read everything a workspace's env depends on, in parallel. `dotenv` is the
276
+ // inheritDotenv-gated merge (the actual base env); `files` keeps per-file detail
277
+ // for the view.
278
+ type WorkspaceEnvState = {
279
+ meta: EnvMeta
280
+ files: DotenvFile[]
281
+ secrets: Record<string, string>
282
+ dotenv: Record<string, string>
283
+ backend: 'keychain' | 'file'
284
+ }
285
+
286
+ async function loadWorkspaceEnvState(workspacePath: string): Promise<WorkspaceEnvState> {
287
+ const store = await secretStore()
288
+ const [meta, files, secrets] = await Promise.all([
289
+ getMeta(workspacePath),
290
+ discoverDotenv(workspacePath),
291
+ store.get(workspacePath)
292
+ ])
293
+ return {
294
+ meta,
295
+ files,
296
+ secrets,
297
+ dotenv: meta.inheritDotenv ? mergeDotenv(files) : {},
298
+ backend: store.backend
299
+ }
300
+ }
301
+
302
+ // ---------------------------------------------------------------------------
303
+ // Public API
304
+ // ---------------------------------------------------------------------------
305
+
306
+ // The effective env for one sink: discovered `.env` (when inherited) overlaid
307
+ // with the custom secrets scoped to that sink. Injected at spawn — env is frozen
308
+ // once the process starts, so changes require a restart (see functions.ts /
309
+ // cc-session.ts).
310
+ export async function resolveWorkspaceEnv(
311
+ workspacePath: string,
312
+ sink: Sink
313
+ ): Promise<Record<string, string>> {
314
+ const { meta, secrets, dotenv } = await loadWorkspaceEnvState(workspacePath)
315
+ const scoped: Record<string, string> = {}
316
+ for (const [k, v] of Object.entries(secrets)) {
317
+ const scope = scopeOf(meta, k)
318
+ if (scope === 'both' || scope === sink) scoped[k] = v
319
+ }
320
+ return { ...dotenv, ...scoped }
321
+ }
322
+
323
+ export type EnvUpdate = {
324
+ // Upsert these custom secret values (write-only).
325
+ set?: Record<string, string>
326
+ // Delete these custom keys.
327
+ remove?: string[]
328
+ // Set the sink scope for existing custom keys.
329
+ scopes?: Record<string, EnvScope>
330
+ // Toggle whether `.env` files feed the workspace.
331
+ inheritDotenv?: boolean
332
+ }
333
+
334
+ // Apply a patch to a workspace's custom secrets + metadata. Patch (not replace)
335
+ // semantics, because values are write-only — the UI can add/update one key
336
+ // without resending the others. Serialized per workspace to avoid lost updates.
337
+ export function updateWorkspaceEnv(workspacePath: string, patch: EnvUpdate): Promise<void> {
338
+ return withWriteLock(resolve(workspacePath), async () => {
339
+ const store = await secretStore()
340
+ const secrets = await store.get(workspacePath)
341
+
342
+ if (patch.set) {
343
+ for (const [k, v] of Object.entries(patch.set)) {
344
+ if (isValidEnvKey(k) && typeof v === 'string') secrets[k] = v
345
+ }
346
+ }
347
+ if (patch.remove) {
348
+ for (const k of patch.remove) delete secrets[k]
349
+ }
350
+ await store.set(workspacePath, secrets)
351
+
352
+ const meta = await getMeta(workspacePath)
353
+ const scopes: Record<string, EnvScope> = {}
354
+ // Keep a scope for every current secret key (default 'both'); drop the rest.
355
+ for (const k of Object.keys(secrets)) scopes[k] = scopeOf(meta, k)
356
+ if (patch.scopes) {
357
+ for (const [k, s] of Object.entries(patch.scopes)) {
358
+ if (k in scopes && isValidScope(s)) scopes[k] = s
359
+ }
360
+ }
361
+ const inheritDotenv =
362
+ typeof patch.inheritDotenv === 'boolean' ? patch.inheritDotenv : meta.inheritDotenv
363
+ await writeMeta(workspacePath, { inheritDotenv, scopes })
364
+ })
365
+ }
366
+
367
+ // The env view for the settings UI: every effective key with its source +
368
+ // scope, the discovered files (key counts only — values masked), the mode flag,
369
+ // the secret backend, and declared-required keys with a satisfied flag.
370
+ // `required` maps a key to the widgets that declared it (collected by caller).
371
+ export async function getWorkspaceEnvView(
372
+ workspacePath: string,
373
+ required: Record<string, string[]> = {}
374
+ ): Promise<WorkspaceEnvView> {
375
+ const { meta, files, secrets, dotenv, backend } = await loadWorkspaceEnvState(workspacePath)
376
+
377
+ const keys = new Set([...Object.keys(dotenv), ...Object.keys(secrets)])
378
+ const vars = [...keys].sort().map(key => {
379
+ const inCustom = key in secrets
380
+ const fromDotenv = key in dotenv
381
+ const source = inCustom && fromDotenv ? 'both' : inCustom ? 'custom' : 'dotenv'
382
+ return {
383
+ key,
384
+ source,
385
+ ...(inCustom ? { scope: scopeOf(meta, key) } : {}),
386
+ ...(fromDotenv ? { files: files.filter(f => key in f.vars).map(f => f.file) } : {})
387
+ }
388
+ })
389
+
390
+ // A widget-declared required key is "satisfied" when it's visible to widgets:
391
+ // a `.env` value (if inherited) or a custom key scoped widgets/both.
392
+ const widgetVisible = new Set(Object.keys(dotenv))
393
+ for (const k of Object.keys(secrets)) {
394
+ if (scopeOf(meta, k) !== 'agent') widgetVisible.add(k)
395
+ }
396
+ const requiredView = Object.entries(required)
397
+ .sort(([a], [b]) => a.localeCompare(b))
398
+ .map(([key, widgets]) => ({ key, satisfied: widgetVisible.has(key), widgets }))
399
+
400
+ return {
401
+ vars,
402
+ files: files.map(f => ({ file: f.file, count: Object.keys(f.vars).length })),
403
+ inheritDotenv: meta.inheritDotenv,
404
+ backend,
405
+ required: requiredView
406
+ }
407
+ }
@@ -0,0 +1,66 @@
1
+ // The one place that knows how to turn a directory into a moi workspace:
2
+ // bundled skills + the `.moi/` scaffold, with the skills location keyed on the
3
+ // agent backend. `moi init`, `moi openclaw init`, and the HTTP API (UI import /
4
+ // create) all provision through here, so a workspace set up from the UI is
5
+ // indistinguishable from one set up via the CLI.
6
+ import { mkdir } from 'node:fs/promises'
7
+ import { homedir } from 'node:os'
8
+ import { join } from 'node:path'
9
+
10
+ import type { WorkspaceType } from '@/lib/types'
11
+
12
+ import { scaffoldMoiDir } from './moi-scaffold'
13
+ import { installBundledSkills } from './skills-template'
14
+
15
+ // Where each backend loads skills from. Claude Code reads `.claude/skills/`;
16
+ // OpenClaw resolves `<workspace>/skills/` with the highest precedence (it wins
17
+ // over same-named bundled or per-user skills). An untyped entry is Claude Code.
18
+ export function skillsDirFor(workspaceRoot: string, type?: WorkspaceType): string {
19
+ return type === 'openclaw'
20
+ ? join(workspaceRoot, 'skills')
21
+ : join(workspaceRoot, '.claude', 'skills')
22
+ }
23
+
24
+ // Folder that holds workspaces created from the UI (`/workspace/create`) — a
25
+ // visible home-dir folder, mirroring how Cowork keeps its session folders under
26
+ // the user's home rather than an app-data dir.
27
+ export const CREATED_WORKSPACES_ROOT = join(homedir(), 'moi')
28
+
29
+ export type ProvisionResult = {
30
+ // Where the skills were installed (backend-dependent, see skillsDirFor).
31
+ skillsDir: string
32
+ // 'exists' when `.moi/` was already bootstrapped, else the bun install exit
33
+ // code (non-zero means deps must be installed manually — not fatal).
34
+ scaffold: 'exists' | number
35
+ }
36
+
37
+ // Lay down everything a workspace needs: create the folder, copy the bundled
38
+ // skills into the backend's skills dir, and bootstrap `.moi/`. Idempotent —
39
+ // re-running refreshes skills and leaves an existing `.moi/` untouched.
40
+ // Registration in the workspace registry is a separate, caller-owned step.
41
+ export async function provisionWorkspace(
42
+ workspaceRoot: string,
43
+ type?: WorkspaceType
44
+ ): Promise<ProvisionResult> {
45
+ const skillsDir = skillsDirFor(workspaceRoot, type)
46
+ await mkdir(workspaceRoot, { recursive: true })
47
+ await installBundledSkills(skillsDir)
48
+ const scaffold = await scaffoldMoiDir(workspaceRoot)
49
+ return { skillsDir, scaffold }
50
+ }
51
+
52
+ // Validate a folder name typed in the create-workspace form. Returns a
53
+ // user-facing error, or null when the name is usable as a single path segment
54
+ // under CREATED_WORKSPACES_ROOT. Leading dots are rejected so a name can never
55
+ // be hidden or collide with `.moi` / `.claude`.
56
+ export function validateWorkspaceFolderName(name: string): string | null {
57
+ if (!name) return 'Folder name is required'
58
+ if (name.length > 64) return 'Folder name is too long (max 64 characters)'
59
+ if (!/^[A-Za-z0-9][A-Za-z0-9._ -]*$/.test(name)) {
60
+ return 'Use letters, numbers, dots, dashes, underscores and spaces, starting with a letter or number'
61
+ }
62
+ if (name.endsWith('.') || name.endsWith(' ')) {
63
+ return 'Folder name cannot end with a dot or space'
64
+ }
65
+ return null
66
+ }
@@ -0,0 +1,109 @@
1
+ Widget design guidelines. Read before creating or modifying any widget.
2
+
3
+ ## The one idea
4
+
5
+ A widget is **glanceable in under 2 seconds** — and earns **one signature moment**: a single expressive flourish (a live visualization, a 3D flip, a tactile surface, a satisfying state change) that makes it feel alive. Restraint everywhere except that one place. If everything is emphasized, nothing is.
6
+
7
+ ## Rules — never break
8
+
9
+ - **Content-only root.** The root is a plain `w-full h-full` rectangle. The host card owns the shell — never put `rounded-*`, an outer `border`, `shadow-*`, or a card-surface background on the root. Use `flex flex-col` + `overflow-hidden`; push footers down with `mt-auto`.
10
+ - **Three states, always.** Loading → skeleton (never a spinner). Error → one human sentence + a retry. Empty → a short prompt, never blank. (Patterns below.)
11
+ - **Height is the hard constraint.** `height = rowSpan×160 + (rowSpan−1)×16`, exact. Width flexes with the viewport. Design for height first; clip risk → `overflow-hidden`, long text → `truncate` / `line-clamp`.
12
+ - **Tailwind for static styling.** No custom CSS, no `@apply`, no *static* `style={{}}`. Icons only from `@tabler/icons-react` (no raw `<svg>`, no other icon packs). Widgets import only from their own folder.
13
+ - **No auto-playing audio or video.** Media is always user-initiated.
14
+ - **No page-level horizontal scroll.** A deliberate, bounded internal scroller (e.g. a Kanban board) is fine; the widget itself never makes the page scroll sideways.
15
+
16
+ ## Sizing
17
+
18
+ Grid: 4 columns · 160px row height · 16px gap. `export const config = { colSpan, rowSpan } as const` (each defaults to 1).
19
+
20
+ | Config | ~Width | Height | Usable (after p-4/5) |
21
+ |--------|--------|--------|----------------------|
22
+ | 1×1 | 284px | 160px | ~252 × 128 |
23
+ | 2×1 | 584px | 160px | ~552 × 128 |
24
+ | 2×2 | 584px | 336px | ~552 × 304 |
25
+ | 4×2 | 1184px | 336px | ~1152 × 304 |
26
+ | 4×3 | 1184px | 512px | ~1152 × 480 |
27
+
28
+ Start at the smallest size that fits; grow only if content demands it. After changing `config` size, rebuild with `moi bundle --force`.
29
+
30
+ ## Defaults — break with intent
31
+
32
+ These are taste, not law. Break any of them when the widget is genuinely better for it — just know you're doing it.
33
+
34
+ - **Background — varies.** Pick a surface that fits the content: a tonal **gradient** (`bg-linear-to-br`, 2–3 stops, one hue family), a **flat metaphor color**, an **image**, or neutral `bg-background`. A soft ambient glow blob (`absolute … rounded-full bg-…/20 blur-3xl`) adds depth. Keep it one family — tonal, not rainbow. Color should mean something (domain, status), not just decorate.
35
+ - **Hierarchy.** One hero element your eye hits first (up to `text-5xl`), ≤2 supporting elements (≤`text-sm`), tertiary muted. The size *gap* is the hierarchy. If two things compete, cut one.
36
+ - **Type.** ≤2 families. Match the hero font to the workspace personality — serif for warmth, geometric/sans for crisp data. `font-mono tabular-nums` for live/changing numbers. Small labels read well uppercase with wide tracking (e.g. `text-[11px] uppercase tracking-[0.2em] text-foreground/60`).
37
+ - **Color tokens.** On neutral surfaces use semantic tokens (`text-foreground`, `text-muted-foreground`, `bg-background`, `border-border`, `text-destructive`). On saturated/gradient surfaces, `text-white` / `text-stone-900` and `white/NN` opacities are correct. Accent colors (a red play button, emerald progress, amber/sky/emerald status dots) signal action or state.
38
+ - **Spacing.** 4px scale. Tight (4–8px) = belongs together; medium (12–16px) = grouped; wide (24px+) = section break. Prefer spacing over dividers. `p-4`/`p-5` content padding; never touch the edges.
39
+ - **Density.** Every element earns its pixel. Prefer live info over static labels. One binary mode toggle (e.g. card/list) is fine — but no tabs, wizards, or multi-step flows.
40
+ - **Family.** Widgets in one workspace should feel related — a shared move (gradient + glow, tracked labels, rounded-pill controls, the same hero font) ties them together.
41
+
42
+ ### Color reference
43
+
44
+ Starting points, not mandates — use them, tint them, or turn an anchor into a 2–3 stop gradient.
45
+
46
+ **Semantic tokens** (for neutral surfaces; auto-resolve to the dark widget theme):
47
+
48
+ | Token | Class | Purpose |
49
+ |-------|-------|---------|
50
+ | Primary text | `text-foreground` | Main content, headings, hero numbers |
51
+ | Secondary text | `text-muted-foreground` | Supporting labels, captions, timestamps |
52
+ | Subdued text | `text-foreground/50` | Lowest-priority metadata |
53
+ | Error text | `text-destructive` | Error messages, destructive states |
54
+ | Surface | `bg-background` | Widget surface (dark) |
55
+ | Raised surface | `bg-card` | Cards within cards, inset areas |
56
+ | Muted surface | `bg-muted` | Subdued backgrounds, skeleton blocks |
57
+ | Secondary surface | `bg-secondary` | Tags, badges, inset regions |
58
+ | Primary action | `bg-primary text-primary-foreground` | Buttons, key interactive elements |
59
+ | Border | `border-border` | Dividers, outlines |
60
+
61
+ **Background anchors by domain** (a tonal base — gradient it or pair with a glow):
62
+
63
+ | Content domain | Anchor colors | Range |
64
+ |----------------|---------------|-------|
65
+ | Weather / sky | `sky-500`, `sky-600`, `blue-600`, `blue-700` | 500–700 |
66
+ | Night / dark sky | `indigo-900`, `slate-800` | 800–900 |
67
+ | Overcast / fog | `slate-500`, `slate-600` | 500–600 |
68
+ | Nature / health | `emerald-600`, `green-600` | 500–700 |
69
+ | Finance / money | `emerald-700`, `teal-600` | 600–700 |
70
+ | Music / audio | `violet-600`, `fuchsia-600` | 500–700 |
71
+ | Alerts / urgent | `red-600`, `orange-600` | 500–700 |
72
+ | Time / clock | `blue-600`, `indigo-600` | 500–700 |
73
+ | Notes / text | `amber-500`, `yellow-500` | 400–600 |
74
+ | Social / comms | `pink-500`, `rose-500` | 400–600 |
75
+ | Productivity | `cyan-600`, `sky-700` | 500–700 |
76
+ | Neutral / generic | `zinc-700`, `neutral-700` | 600–800 |
77
+
78
+ ## Motion & interaction
79
+
80
+ - **Layered, but ranked.** (1) one **entrance** (`animate-in fade-in-0 zoom-in-95`, may stagger via a dynamic `animationDelay`); (2) **feedback** on every interaction (hover lift, `active:scale-[0.98]`, optimistic toggles, `transition-colors`, `disabled:opacity-50`); (3) **≤1 signature** animation (a waveform, a flip, confetti). Never two signatures in one widget. Don't animate a frequently-updating number — just swap it.
81
+ - **Dynamic `style` is allowed — for data only.** Use `style={{}}` solely for genuinely dynamic, computed values: per-frame transforms, data-driven widths/heights, per-index stagger delays, flip rotations. Everything static stays in Tailwind.
82
+ - **Tactility (optional, ≤1 per widget).** Interactive surfaces (keys, cards, toggles) may feel physical with an inset top-sheen + soft drop shadow + inset ring, e.g. `shadow-[inset_0_1px_0_rgba(255,255,255,0.4),0_3px_6px_rgba(0,0,0,0.3)] ring-1 ring-inset ring-white/20`. Never on the root.
83
+
84
+ ## States
85
+
86
+ **Loading** — a skeleton that mirrors the real layout (vary block widths), keeping the background:
87
+ ```tsx
88
+ <div className="h-3 w-20 rounded bg-foreground/20 animate-pulse" />
89
+ ```
90
+ **Error** — drop to `bg-background`, one sentence, a retry:
91
+ ```tsx
92
+ <div className="flex h-full w-full flex-col items-center justify-center gap-2 bg-background p-4 text-center">
93
+ <Icon size={24} stroke={1.5} className="text-muted-foreground" />
94
+ <span className="text-xs text-destructive">Could not load</span>
95
+ <button onClick={retry} className="text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground">
96
+ Try again
97
+ </button>
98
+ </div>
99
+ ```
100
+ **Empty** — a short prompt, never blank. **Refresh** — keep current data visible (use a separate `refreshing` flag, `animate-spin` the button). **Stale** — a `text-foreground/50` timestamp pinned to the bottom with `mt-auto`, re-rendered on an interval.
101
+
102
+ ## Helper
103
+
104
+ Widgets can't import the project `cn`. Use a local `cx()`; never template-literal ternaries in `className`:
105
+ ```tsx
106
+ function cx(...classes: (string | false | undefined | null)[]) {
107
+ return classes.filter(Boolean).join(' ')
108
+ }
109
+ ```
@@ -0,0 +1,57 @@
1
+ # Scratchpad
2
+
3
+ The Scratchpad is the workspace's **shared whiteboard** — one freeform tldraw canvas the user
4
+ draws on by hand and you drive through `moi scratch`. Same canvas, two authors; disk is the
5
+ source of truth. Use it to sketch, diagram, annotate the user's drawing, or lay out boxes.
6
+
7
+ ## Seeing
8
+
9
+ **Always inspect the canvas through the commands below — never open, `cat`, `read`, or parse the
10
+ snapshot file yourself.** The on-disk file (`.moi/.scratchpad.json`) is moi-internal: its schema is
11
+ tldraw's and shifts without notice, blobs are stripped, and `moi scratch read` already gives you the
12
+ clean, agent-friendly view. Treat it exactly like `.moi/.workspace.json` — CLI only.
13
+
14
+ - `moi scratch read` — dump the canvas as JSON: each shape's `id`, `type`, position, size, and
15
+ text. Off disk, so it works whether or not a browser tab is open.
16
+ - `moi scratch read-image <id>` — save one image shape to a file (its actual bytes; `read` omits
17
+ the blob). Off disk too.
18
+ - `moi scratch view` — render the whole canvas to a PNG. Needs an open Scratchpad tab.
19
+
20
+ `read` is for logic; `view` / `read-image` are for vision.
21
+
22
+ ## Drawing
23
+
24
+ ```
25
+ moi scratch add text --at <x,y> --text "..." [--id NAME] [--color C] [--font-size S]
26
+ moi scratch add rect --at <x,y> --size <w,h> [--text] [--id NAME] [--color C] [--fill F] [--font-size S]
27
+ moi scratch add note --at <x,y> --text "..." [--id NAME] [--color C] [--font-size S]
28
+ moi scratch add arrow --from <id|x,y> --to <id|x,y> [--id NAME] [--color C] [--stroke W] [--elbow]
29
+ moi scratch add image <path> [--at <x,y>] [--id NAME] [--quality lo|hi]
30
+ moi scratch move <id> --to <x,y>
31
+ moi scratch set <id> --text "..."
32
+ moi scratch delete <id>
33
+ moi scratch clear
34
+ ```
35
+
36
+ - `--id` names a shape so later commands can address it (`move` / `set` / `delete`, or as an
37
+ arrow endpoint). Without it, the command prints the generated id.
38
+ - `add arrow --from box1 --to box2` binds endpoints to those shapes, so the arrow follows when
39
+ they move. Endpoints can also be bare `x,y`. `--elbow` routes with right angles.
40
+ - `add image` resizes to fit the canvas — `--quality lo` (default) or `hi` for more pixels — so a
41
+ huge file never gets embedded whole.
42
+ - `--color` is `black|red|yellow|green|blue|grey` or any hex (snapped to nearest). The other style
43
+ flags mirror each shape's toolbar controls: `--fill` (rect) is `none|semi|pattern|solid`;
44
+ `--font-size` (text, note, and a rect's label) is `regular|big`; `--stroke` (arrow) is
45
+ `small|large`. You can only make what the user can make by hand.
46
+ - `--fill` picks how a rectangle's interior is painted (the outline is always the full `--color`):
47
+ - `none` — transparent interior, just the colored outline. Reach for this to box/group other
48
+ shapes without hiding them, or when the rect is a frame.
49
+ - `semi` — a light, translucent wash of the color. Soft highlight; text and shapes underneath
50
+ still read through it.
51
+ - `pattern` — diagonal hatch lines in the color over a near-transparent interior. Reads as
52
+ "marked / selected / special" without going fully opaque.
53
+ - `solid` — fully opaque fill in the color (interior matches the outline). Use for solid blocks,
54
+ legend keys, or a label chip; anything behind it is hidden.
55
+ A rect's outline is always a rough (hand-drawn) stroke, matching what the toolbar draws. Default
56
+ fill is `semi`; pass `--fill none` for an outline-only box or `--fill solid` for an opaque block.
57
+ - Coordinates are tldraw canvas space (origin top-left, y down).