moi-computer 0.1.3 → 0.2.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "moi-computer",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "Local AI workspace powered by the Claude Agent SDK, Bun, React, and Tailwind. Requires Bun.",
5
5
  "license": "Elastic-2.0",
6
6
  "type": "module",
@@ -44,7 +44,7 @@
44
44
  "!workspace/.moi"
45
45
  ],
46
46
  "scripts": {
47
- "dev": "bun server/cli.ts start --dev",
47
+ "dev": "bun server/cli.ts start --dev --debug",
48
48
  "build:client": "bun scripts/build-client.ts",
49
49
  "vendor:react": "bun scripts/build-vendor.ts",
50
50
  "prepack": "bun scripts/build-client.ts",
@@ -89,7 +89,7 @@
89
89
  "sugar-high": "^1.2.1",
90
90
  "tailwind-merge": "^3.5.0",
91
91
  "tailwindcss": "^4.1.11",
92
- "tldraw": "^5.1.1",
92
+ "tldraw": "5.2.3",
93
93
  "tw-animate-css": "^1.4.0",
94
94
  "typescript": "^5.9.3",
95
95
  "wouter": "^3.9.0",
package/server/api.ts CHANGED
@@ -4,18 +4,12 @@ import { createMiddleware } from 'hono/factory'
4
4
  import { existsSync } from 'node:fs'
5
5
  import { basename, join, resolve } from 'node:path'
6
6
 
7
- import type {
8
- EnvScope,
9
- UploadInfo,
10
- WorkspaceEntry,
11
- WorkspaceModels,
12
- WorkspaceType
13
- } from '@/lib/types'
7
+ import type { UploadInfo, WorkspaceEntry, WorkspaceModels, WorkspaceType } from '@/lib/types'
14
8
 
15
9
  import { getClaudeModels } from './agent'
16
10
  import { apiBaseFor, parseAppletTail, serveWorkspaceFile } from './applets'
17
- import { restartWorkspaceSessions } from './cc-session'
18
- import { callFunction, parseFunctionPath, restartWorker } from './functions'
11
+ import { applyEnvChanged } from './env-apply'
12
+ import { callFunction, parseFunctionPath } from './functions'
19
13
  import { processIcon } from './icon'
20
14
  import { getWorkspacePreview, loadLayout, mergeLayoutForSave, saveLayout } from './layout'
21
15
  import { getMcpStatus } from './mcp'
@@ -38,42 +32,22 @@ import { getThreadConfig, saveThreadConfig } from './thread-config'
38
32
  import type { ThreadConfigPatch } from './thread-config'
39
33
  import { serveWorkspaceImagePreview } from './preview'
40
34
  import { MAX_UPLOAD_BYTES, addUpload, getUpload } from './uploads'
41
- import { collectViewRequiredEnv, listViews, serveView } from './views'
42
- import { collectRequiredEnv, listWidgets, serveWidget } from './widgets'
35
+ import { requiredEnvFor } from './required-env'
36
+ import { listViews, serveView } from './views'
37
+ import { listWidgets, serveWidget } from './widgets'
43
38
  import { getWorkspaceConfig, setWorkspaceConfig } from './workspace-config'
44
39
  import {
45
40
  CREATED_WORKSPACES_ROOT,
46
41
  provisionWorkspace,
47
42
  validateWorkspaceFolderName
48
43
  } from './workspace-init'
49
- import {
50
- getWorkspaceEnvView,
51
- isValidEnvKey,
52
- isValidScope,
53
- updateWorkspaceEnv
54
- } from './workspace-env'
44
+ import { getWorkspaceEnvView, isValidEnvKey, updateWorkspaceEnv } from './workspace-env'
55
45
  import type { EnvUpdate } from './workspace-env'
56
46
 
57
47
  // The resolved workspace is stashed on the context by `withWorkspace`, so every
58
48
  // `/api/workspaces/:id/*` handler can read it without re-querying the registry.
59
49
  type ApiEnv = { Variables: { ws: WorkspaceEntry } }
60
50
 
61
- // The env "required" view aggregates `config.requiredEnv` declared by both
62
- // widgets and views, each key mapped to the bundle ids that asked for it.
63
- async function requiredEnvFor(workspacePath: string): Promise<Record<string, string[]>> {
64
- const [widgets, views] = await Promise.all([
65
- collectRequiredEnv(workspacePath),
66
- collectViewRequiredEnv(workspacePath)
67
- ])
68
- const out: Record<string, string[]> = {}
69
- for (const map of [widgets, views]) {
70
- for (const [key, ids] of Object.entries(map)) {
71
- out[key] = [...(out[key] ?? []), ...ids]
72
- }
73
- }
74
- return out
75
- }
76
-
77
51
  async function handleFunctionCall(
78
52
  req: Request,
79
53
  tail: string,
@@ -303,11 +277,12 @@ one.get('/mcp', async c => {
303
277
  // custom secrets + scopes + declared-required keys; values masked).
304
278
  one.get('/env', async c => {
305
279
  const ws = c.get('ws')
306
- const required = await requiredEnvFor(ws.path)
307
- return c.json(await getWorkspaceEnvView(ws.path, required))
280
+ // Unawaited on purpose: getWorkspaceEnvView loads it in parallel with the
281
+ // env stores (manifest reads and env reads are independent).
282
+ return c.json(await getWorkspaceEnvView(ws.path, requiredEnvFor(ws.path)))
308
283
  })
309
284
 
310
- // PUT patches custom secrets (set/remove/scopes) and/or the inheritDotenv mode,
285
+ // PUT patches custom secrets (set/remove) and/or the inheritDotenv mode,
311
286
  // then reaps the workspace's function worker and idle agent sessions so the next
312
287
  // call/message picks up the change (env is frozen at spawn — a hard restart is
313
288
  // the only way).
@@ -336,15 +311,6 @@ one.put('/env', async c => {
336
311
  }
337
312
  patch.remove = body.remove as string[]
338
313
  }
339
- if (body.scopes !== undefined) {
340
- if (typeof body.scopes !== 'object' || body.scopes === null) {
341
- return c.text('scopes must be an object', 400)
342
- }
343
- for (const [k, s] of Object.entries(body.scopes)) {
344
- if (!isValidScope(s)) return c.text(`Invalid scope for ${k}`, 400)
345
- }
346
- patch.scopes = body.scopes as Record<string, EnvScope>
347
- }
348
314
  if (body.inheritDotenv !== undefined) {
349
315
  if (typeof body.inheritDotenv !== 'boolean') {
350
316
  return c.text('inheritDotenv must be a boolean', 400)
@@ -355,19 +321,14 @@ one.put('/env', async c => {
355
321
  // Skip the write + reaps for a no-op PUT (no recognized fields) so an empty
356
322
  // body doesn't needlessly kill warm workers / idle sessions.
357
323
  const hasChange =
358
- patch.set !== undefined ||
359
- patch.remove !== undefined ||
360
- patch.scopes !== undefined ||
361
- patch.inheritDotenv !== undefined
324
+ patch.set !== undefined || patch.remove !== undefined || patch.inheritDotenv !== undefined
362
325
  if (hasChange) {
363
326
  await updateWorkspaceEnv(ws.path, patch)
364
- // Frozen-at-spawn: reap workers/idle sessions so fresh env takes effect.
365
- restartWorker(ws.path)
366
- restartWorkspaceSessions(ws.path)
327
+ // Frozen-at-spawn: reap workers/idle sessions and tell other clients.
328
+ applyEnvChanged(ws)
367
329
  }
368
330
 
369
- const required = await requiredEnvFor(ws.path)
370
- return c.json(await getWorkspaceEnvView(ws.path, required))
331
+ return c.json(await getWorkspaceEnvView(ws.path, requiredEnvFor(ws.path)))
371
332
  })
372
333
 
373
334
  // Models the workspace's agent backend can run, normalized across providers.
@@ -298,6 +298,18 @@ function appletRuntimePlugin(
298
298
  loader: 'js'
299
299
  }))
300
300
 
301
+ // `devalue` is moi's OWN dependency, injected into every applet bundle via
302
+ // the mei:rpc virtual module above. A virtual module has no on-disk
303
+ // location, so Bun resolves the bare `devalue` specifier against the
304
+ // process cwd's node_modules — which breaks when the server runs from a
305
+ // neutral cwd (a prebuilt/global install; see serverCwd in cli.ts). A
306
+ // resolveDir on the onLoad is ignored for bare specifiers in Bun 1.3, so
307
+ // pin it to an absolute path inside moi's OWN package (this file's dir
308
+ // walks up to moi's node_modules), making the applet build cwd-independent.
309
+ build.onResolve({ filter: /^devalue$/ }, () => ({
310
+ path: Bun.resolveSync('devalue', import.meta.dir)
311
+ }))
312
+
301
313
  // The `moi` runtime module (fileUrl). A bare specifier, so match it exactly.
302
314
  build.onResolve({ filter: /^moi$/ }, () => ({ path: 'moi', namespace: 'moi-runtime' }))
303
315
  build.onLoad({ filter: /.*/, namespace: 'moi-runtime' }, () => ({
@@ -534,7 +534,7 @@ export async function sendCCMessage(input: {
534
534
  effort: input.effort,
535
535
  stream: wantStream,
536
536
  // The agent only sees secrets scoped to the 'agent' sink (plus .env).
537
- workspaceEnv: await resolveWorkspaceEnv(input.workspacePath, 'agent')
537
+ workspaceEnv: await resolveWorkspaceEnv(input.workspacePath)
538
538
  })
539
539
  }
540
540
 
@@ -0,0 +1,238 @@
1
+ // CLI face over the workspace env model (workspace-env.ts): rendering for
2
+ // `moi env`, secret-value input for `moi env set`, the exec spawn, and the
3
+ // control-port notification that lets a running server pick up CLI writes.
4
+ //
5
+ // Secret VALUES never pass through here except on their way into a spawned
6
+ // process (`execWithEnv`) or the secret store (`set` reads stdin/argv). Nothing
7
+ // in this module prints a value.
8
+ import pc from 'picocolors'
9
+
10
+ import type { WorkspaceEntry, WorkspaceEnvView } from '@/lib/types'
11
+
12
+ import { columns } from './cli-ui'
13
+ import { CONTROL_PORT } from './constants'
14
+ import { findWorkspaceForPath, listWorkspaces } from './registry'
15
+ import { discoverDotenvKeys, resolveWorkspaceEnv } from './workspace-env'
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Workspace resolution: cwd → nearest registered workspace
19
+ // ---------------------------------------------------------------------------
20
+
21
+ // Every `moi env` subcommand targets the workspace containing cwd (same
22
+ // semantics as the control server's resolveWorkspace — works from `.moi/` or
23
+ // any subdirectory). Exits with a hint when cwd is outside every workspace, so
24
+ // a typo never creates an orphan env entry keyed to a phantom path.
25
+ export async function resolveCwdWorkspace(): Promise<WorkspaceEntry> {
26
+ const match = findWorkspaceForPath(await listWorkspaces(), process.cwd())
27
+ if (!match) {
28
+ console.error(
29
+ '\n' +
30
+ pc.red('✗') +
31
+ ` ${process.cwd()} is not inside a registered moi workspace.\n` +
32
+ pc.dim(' Open it in moi, or run from the workspace root.\n')
33
+ )
34
+ process.exit(1)
35
+ }
36
+ return match
37
+ }
38
+
39
+ // ---------------------------------------------------------------------------
40
+ // `moi env` rendering
41
+ // ---------------------------------------------------------------------------
42
+
43
+ function renderDotenvSection(view: WorkspaceEnvView): string[] {
44
+ const out: string[] = []
45
+ const state = view.inheritDotenv
46
+ ? pc.dim('inherited: on')
47
+ : pc.yellow('inherited: off') + pc.dim(' (disabled in settings — keys not injected)')
48
+ out.push(`${pc.bold('.env files')} ${state}`)
49
+ if (view.files.length === 0) {
50
+ out.push(pc.dim(' none detected'))
51
+ } else {
52
+ const width = Math.max(...view.files.map(f => f.file.length))
53
+ for (const f of view.files) {
54
+ out.push(
55
+ ` ${f.file.padEnd(width)} ${pc.dim(`${f.count} ${f.count === 1 ? 'key' : 'keys'}`)}`
56
+ )
57
+ }
58
+ }
59
+ return out
60
+ }
61
+
62
+ function sourceLabel(v: WorkspaceEnvView['vars'][number]): string {
63
+ // A dotenv-sourced key names its file(s); `both` is a custom secret shadowing
64
+ // a `.env` value (custom wins).
65
+ if (v.source === 'custom') return 'custom'
66
+ const files = (v.files ?? []).join(', ')
67
+ return v.source === 'both' ? `custom ${pc.dim(`(overrides ${files})`)}` : files
68
+ }
69
+
70
+ // The full diagnostic view: vars with sources, dotenv state (files listed even
71
+ // when disabled), required-key satisfaction, and the secret backend. No values.
72
+ export function renderEnvView(entry: WorkspaceEntry, view: WorkspaceEnvView): string {
73
+ const lines: string[] = []
74
+ const name = entry.name ? ` (${entry.name})` : ''
75
+ lines.push(`${pc.bold('Workspace:')} ${entry.displayPath ?? entry.path}${pc.dim(name)}`)
76
+ lines.push('')
77
+ lines.push(...renderDotenvSection(view))
78
+ lines.push('')
79
+
80
+ if (view.vars.length === 0) {
81
+ lines.push(pc.dim('No env vars — add secrets in the workspace env settings, or create a .env.'))
82
+ } else {
83
+ lines.push(
84
+ columns(
85
+ ['KEY', 'SOURCE'].map(h => pc.dim(h)),
86
+ view.vars.map(v => [v.key, sourceLabel(v)]),
87
+ ''
88
+ )
89
+ )
90
+ }
91
+
92
+ if (view.required.length > 0) {
93
+ lines.push('')
94
+ lines.push(pc.bold('Required by widgets/views'))
95
+ const width = Math.max(...view.required.map(r => r.key.length))
96
+ for (const r of view.required) {
97
+ const mark = r.satisfied ? pc.green('✓') : pc.red('✗')
98
+ const who = r.widgets.join(', ')
99
+ lines.push(
100
+ r.satisfied
101
+ ? ` ${mark} ${r.key.padEnd(width)} ${pc.dim(who)}`
102
+ : ` ${mark} ${r.key.padEnd(width)} missing — required by ${who}`
103
+ )
104
+ }
105
+ }
106
+
107
+ lines.push('')
108
+ lines.push(
109
+ pc.dim(`Secrets stored in: ${view.backend === 'keychain' ? 'OS keychain' : 'file (0600)'}`)
110
+ )
111
+ return lines.join('\n')
112
+ }
113
+
114
+ // ---------------------------------------------------------------------------
115
+ // `moi env set` value input
116
+ // ---------------------------------------------------------------------------
117
+
118
+ // Read a secret from a TTY without echoing: raw mode, chars collected until
119
+ // Enter, backspace honored, Ctrl-C aborts. The prompt goes to stderr so even a
120
+ // redirected stdout captures no trace of the interaction.
121
+ function readSecretFromTty(promptText: string): Promise<string> {
122
+ process.stderr.write(promptText)
123
+ const stdin = process.stdin
124
+ stdin.setRawMode(true)
125
+ stdin.resume()
126
+ let value = ''
127
+ return new Promise((resolve, reject) => {
128
+ const cleanup = () => {
129
+ stdin.setRawMode(false)
130
+ stdin.pause()
131
+ stdin.off('data', onData)
132
+ process.stderr.write('\n')
133
+ }
134
+ const onData = (chunk: Buffer) => {
135
+ for (const ch of chunk.toString('utf8')) {
136
+ if (ch === '\r' || ch === '\n') {
137
+ cleanup()
138
+ resolve(value)
139
+ return
140
+ }
141
+ if (ch === '\u0003') {
142
+ cleanup()
143
+ reject(new Error('Aborted'))
144
+ return
145
+ }
146
+ if (ch === '\u007f' || ch === '\b') value = value.slice(0, -1)
147
+ else value += ch
148
+ }
149
+ }
150
+ stdin.on('data', onData)
151
+ })
152
+ }
153
+
154
+ // The value for a bare `moi env set KEY`: hidden TTY prompt for humans, piped
155
+ // stdin for scripts (one trailing newline trimmed, so `echo $V | moi env set K`
156
+ // stores exactly $V).
157
+ export async function readSecretValue(key: string): Promise<string> {
158
+ if (process.stdin.isTTY) return readSecretFromTty(`Value for ${key} (hidden): `)
159
+ return (await Bun.stdin.text()).replace(/\r?\n$/, '')
160
+ }
161
+
162
+ // ---------------------------------------------------------------------------
163
+ // Server notification after a CLI write
164
+ // ---------------------------------------------------------------------------
165
+
166
+ // Env is frozen at spawn — a running server must reap the widget worker and
167
+ // idle agent sessions for a CLI write to take effect (mirrors PUT /env). Sends
168
+ // `env:changed` over the control port; resolves false when no server is
169
+ // running (fine: the next server start resolves fresh env anyway).
170
+ export function notifyEnvChanged(path: string): Promise<boolean> {
171
+ return new Promise(resolve => {
172
+ let ws: WebSocket
173
+ try {
174
+ ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
175
+ } catch {
176
+ resolve(false)
177
+ return
178
+ }
179
+ const timer = setTimeout(() => {
180
+ try {
181
+ ws.close()
182
+ } catch {}
183
+ resolve(false)
184
+ }, 1500)
185
+ ws.onopen = () => ws.send(JSON.stringify({ type: 'env:changed', path }))
186
+ ws.onmessage = event => {
187
+ clearTimeout(timer)
188
+ ws.close()
189
+ // A malformed reply must still settle the promise — the CLI awaits this.
190
+ try {
191
+ const res: unknown = JSON.parse(String(event.data))
192
+ resolve(typeof res === 'object' && res !== null && (res as { ok?: unknown }).ok === true)
193
+ } catch {
194
+ resolve(false)
195
+ }
196
+ }
197
+ ws.onerror = () => {
198
+ clearTimeout(timer)
199
+ resolve(false)
200
+ }
201
+ })
202
+ }
203
+
204
+ // ---------------------------------------------------------------------------
205
+ // `moi env exec`
206
+ // ---------------------------------------------------------------------------
207
+
208
+ // Run `cmd` with the workspace env overlaid on the inherited process env — the
209
+ // workspace resolution wins, so re-resolved values override a stale agent-
210
+ // session snapshot. Returns the child's exit code; 127 when the binary is
211
+ // missing.
212
+ export async function execWithEnv(workspacePath: string, cmd: string[]): Promise<number> {
213
+ const [resolved, dotenvKeys] = await Promise.all([
214
+ resolveWorkspaceEnv(workspacePath),
215
+ discoverDotenvKeys(workspacePath)
216
+ ])
217
+ // Bun auto-loads the workspace `.env` into THIS process when the CLI runs
218
+ // from the workspace root, so the inherited env is not trustworthy for
219
+ // workspace keys — scrub them and let the resolution re-add what actually
220
+ // applies (otherwise `inheritDotenv: off` still leaks `.env` values).
221
+ const base: Record<string, string | undefined> = { ...process.env }
222
+ for (const key of dotenvKeys) delete base[key]
223
+ const env = { ...base, ...resolved }
224
+ try {
225
+ const proc = Bun.spawn(cmd, {
226
+ cwd: process.cwd(),
227
+ env,
228
+ stdin: 'inherit',
229
+ stdout: 'inherit',
230
+ stderr: 'inherit'
231
+ })
232
+ return await proc.exited
233
+ } catch (err) {
234
+ const msg = err instanceof Error ? err.message : String(err)
235
+ console.error(pc.red('✗') + ` Could not run ${cmd[0]}: ${msg}`)
236
+ return 127
237
+ }
238
+ }