moi-computer 0.1.4 → 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.4",
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.
@@ -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
+ }
package/server/cli.ts CHANGED
@@ -18,6 +18,13 @@ import type {
18
18
  ScratchStyle
19
19
  } from '@/lib/types'
20
20
 
21
+ import {
22
+ execWithEnv,
23
+ notifyEnvChanged,
24
+ readSecretValue,
25
+ renderEnvView,
26
+ resolveCwdWorkspace
27
+ } from './cli-env'
21
28
  import { columns } from './cli-ui'
22
29
  import { CONTROL_PORT, PORT } from './constants'
23
30
  import { type OpenClawAgent, discoverOpenClawAgents } from './openclaw'
@@ -32,6 +39,12 @@ import {
32
39
  staleSkillNotice
33
40
  } from './skill-version'
34
41
  import { installBundledSkills } from './skills-template'
42
+ import {
43
+ getWorkspaceEnvView,
44
+ isValidEnvKey,
45
+ secretBackend,
46
+ updateWorkspaceEnv
47
+ } from './workspace-env'
35
48
  import { provisionWorkspace, skillsDirFor } from './workspace-init'
36
49
 
37
50
  // ---- helpers ----------------------------------------------------------------
@@ -665,6 +678,164 @@ const status = defineCommand({
665
678
  }
666
679
  })
667
680
 
681
+ // ---- env subcommands --------------------------------------------------------
682
+
683
+ function envFail(message: string): never {
684
+ console.error('\n' + pc.red('✗') + ' ' + message + '\n')
685
+ process.exit(1)
686
+ }
687
+
688
+ const envSet = defineCommand({
689
+ meta: {
690
+ name: 'set',
691
+ description:
692
+ 'Set custom secrets: `moi env set KEY=value [KEY=value...]`, or `moi env set KEY` to read one value from stdin'
693
+ },
694
+ args: {
695
+ key: {
696
+ type: 'positional',
697
+ required: true,
698
+ description: 'KEY=value pair(s), or a single bare KEY to read the value from stdin'
699
+ }
700
+ },
701
+ async run({ args }) {
702
+ const entry = await resolveCwdWorkspace()
703
+ const pairs = args._
704
+ const set: Record<string, string> = {}
705
+
706
+ if (pairs.length === 1 && !pairs[0].includes('=')) {
707
+ // Bare-KEY form: one key, value from stdin (hidden prompt on a TTY).
708
+ const key = pairs[0]
709
+ if (!isValidEnvKey(key)) envFail(`Invalid env key: ${key}`)
710
+ let value: string
711
+ try {
712
+ value = await readSecretValue(key)
713
+ } catch {
714
+ // Ctrl-C at the hidden prompt.
715
+ process.exit(1)
716
+ }
717
+ // An empty value is almost always an unset variable on the piping side —
718
+ // storing '' would silently shadow a real .env value with nothing.
719
+ if (value === '')
720
+ envFail(`Empty value for ${key} — pipe a non-empty value or pass ${key}=value`)
721
+ set[key] = value
722
+ } else {
723
+ for (const pair of pairs) {
724
+ const eq = pair.indexOf('=')
725
+ if (eq === -1) {
726
+ envFail(
727
+ `Missing value for ${pair} — use KEY=value (bare KEY reads stdin only when set alone)`
728
+ )
729
+ }
730
+ const key = pair.slice(0, eq)
731
+ const value = pair.slice(eq + 1)
732
+ if (!isValidEnvKey(key)) envFail(`Invalid env key: ${key}`)
733
+ if (value === '')
734
+ envFail(`Empty value for ${key} — use \`moi env unset ${key}\` to remove a key`)
735
+ set[key] = value
736
+ }
737
+ }
738
+
739
+ await updateWorkspaceEnv(entry.path, { set })
740
+ await notifyEnvChanged(entry.path)
741
+ for (const key of Object.keys(set)) {
742
+ console.log(pc.green('✓') + ` Set ${pc.bold(key)} ${pc.dim('(custom)')}`)
743
+ }
744
+ // A plaintext fallback should never go unnoticed at write time.
745
+ if ((await secretBackend()) === 'file') {
746
+ console.log(pc.dim(' Stored in a 0600 file — OS keychain unavailable.'))
747
+ }
748
+ process.exit(0)
749
+ }
750
+ })
751
+
752
+ const envUnset = defineCommand({
753
+ meta: { name: 'unset', description: 'Remove custom secrets: `moi env unset KEY [KEY...]`' },
754
+ args: {
755
+ key: { type: 'positional', required: true, description: 'Key(s) to remove' }
756
+ },
757
+ async run({ args }) {
758
+ const entry = await resolveCwdWorkspace()
759
+ const view = await getWorkspaceEnvView(entry.path)
760
+ const byKey = new Map(view.vars.map(v => [v.key, v]))
761
+
762
+ // Only custom secrets are removable; a dotenv-sourced key lives in its file.
763
+ const removable: string[] = []
764
+ let hadError = false
765
+ for (const key of args._) {
766
+ const v = byKey.get(key)
767
+ if (!v) {
768
+ console.warn(pc.yellow('!') + ` ${key} is not set — skipping`)
769
+ continue
770
+ }
771
+ if (v.source === 'dotenv') {
772
+ console.error(
773
+ pc.red('✗') +
774
+ ` ${key} comes from ${(v.files ?? []).join(', ')} — edit that file instead` +
775
+ pc.dim(' (moi env unset only removes custom secrets)')
776
+ )
777
+ hadError = true
778
+ continue
779
+ }
780
+ removable.push(key)
781
+ }
782
+
783
+ if (removable.length > 0) {
784
+ await updateWorkspaceEnv(entry.path, { remove: removable })
785
+ await notifyEnvChanged(entry.path)
786
+ for (const key of removable) {
787
+ const v = byKey.get(key)
788
+ const unshadow =
789
+ v?.source === 'both' ? pc.dim(` (falls back to ${(v.files ?? []).join(', ')})`) : ''
790
+ console.log(pc.green('✓') + ` Removed ${pc.bold(key)}${unshadow}`)
791
+ }
792
+ }
793
+ process.exit(hadError ? 1 : 0)
794
+ }
795
+ })
796
+
797
+ const envExec = defineCommand({
798
+ meta: {
799
+ name: 'exec',
800
+ description: 'Run a command with the workspace env: `moi env exec -- <cmd> [args...]`'
801
+ },
802
+ async run({ rawArgs }) {
803
+ // Everything after `--` is the child command, untouched by flag parsing.
804
+ const sep = rawArgs.indexOf('--')
805
+ const cmd = sep === -1 ? [] : rawArgs.slice(sep + 1)
806
+ if (cmd.length === 0) {
807
+ console.error('\n' + pc.red('✗') + ' Usage: moi env exec -- <cmd> [args...]\n')
808
+ process.exit(1)
809
+ }
810
+ const entry = await resolveCwdWorkspace()
811
+ process.exit(await execWithEnv(entry.path, cmd))
812
+ }
813
+ })
814
+
815
+ const envSubCommands = { set: envSet, unset: envUnset, exec: envExec }
816
+
817
+ const env = defineCommand({
818
+ meta: {
819
+ name: 'env',
820
+ description: 'Show the workspace env (key names only — never values)'
821
+ },
822
+ subCommands: envSubCommands,
823
+ async run({ rawArgs }) {
824
+ // citty invokes the parent run even after dispatching a subcommand — only
825
+ // render the table when no subcommand ran. Object.hasOwn so prototype
826
+ // names ('constructor', 'toString') never count as a dispatched command.
827
+ const first = rawArgs.find(a => !a.startsWith('-'))
828
+ if (first && Object.hasOwn(envSubCommands, first)) return
829
+ const entry = await resolveCwdWorkspace()
830
+ // Lazy: required-env pulls the widget/view bundler chain (TS compiler),
831
+ // which must not load for every other `moi` command's startup.
832
+ const { requiredEnvFor } = await import('./required-env')
833
+ const view = await getWorkspaceEnvView(entry.path, requiredEnvFor(entry.path))
834
+ console.log('\n' + renderEnvView(entry, view) + '\n')
835
+ process.exit(0)
836
+ }
837
+ })
838
+
668
839
  // ---- openclaw subcommands ---------------------------------------------------
669
840
 
670
841
  // Match an `agent` argument against `agentId` (exact) or `name`
@@ -1549,6 +1720,7 @@ const main = defineCommand({
1549
1720
  refresh,
1550
1721
  theme,
1551
1722
  config,
1723
+ env,
1552
1724
  status,
1553
1725
  openclaw,
1554
1726
  scratch,
package/server/control.ts CHANGED
@@ -3,6 +3,7 @@ import { resolve } from 'path'
3
3
  import type { WorkspaceEntry } from '@/lib/types'
4
4
 
5
5
  import { CONTROL_PORT } from './constants'
6
+ import { applyEnvChanged } from './env-apply'
6
7
  import { processIcon } from './icon'
7
8
  import { loadLayout, saveLayout } from './layout'
8
9
  import { publishEvent } from './events'
@@ -114,6 +115,16 @@ export const control = Bun.serve({
114
115
  return
115
116
  }
116
117
 
118
+ if (data.type === 'env:changed') {
119
+ // A CLI env write (`moi env set`/`unset`) already landed on disk —
120
+ // reap + broadcast so it takes effect (same path as PUT /env).
121
+ const match = await resolveWorkspace(ws, data.path)
122
+ if (!match) return
123
+ applyEnvChanged(match)
124
+ ws.send(JSON.stringify({ ok: true }))
125
+ return
126
+ }
127
+
117
128
  if (data.type === 'theme') {
118
129
  // Theme is per-workspace — resolve to the real root (subdir-safe).
119
130
  const match = await resolveWorkspace(ws, data.path)
@@ -0,0 +1,9 @@
1
+ // Single source of truth for the OS data dir holding moi's global state
2
+ // (workspaces.json, thread-config.json, workspace-env.json, …).
3
+ //
4
+ // MOI_DATA_DIR overrides it wholesale. This is the isolation seam for CLI
5
+ // e2e tests: env-paths only honors XDG_DATA_HOME on Linux, so on macOS a
6
+ // spawned CLI would otherwise read the developer's real data dir.
7
+ import envPaths from 'env-paths'
8
+
9
+ export const DATA_DIR = process.env.MOI_DATA_DIR || envPaths('moi', { suffix: false }).data
@@ -0,0 +1,16 @@
1
+ // The one place an env change takes effect. Env is frozen at spawn, so after
2
+ // any write — the settings UI's PUT /env or a CLI `moi env set`/`unset`
3
+ // relayed over the control port — the workspace's processes must be reaped and
4
+ // every connected client told to refetch. Both entry points call this so the
5
+ // side effects can never drift apart.
6
+ import { restartWorkspaceSessions } from './cc-session'
7
+ import { publishEvent } from './events'
8
+ import { restartWorker } from './functions'
9
+
10
+ export function applyEnvChanged(workspace: { id: string; path: string }): void {
11
+ // Kill the cached widget worker (next RPC respawns with fresh env) and tear
12
+ // down idle agent sessions (busy ones keep their snapshot until turn end).
13
+ restartWorker(workspace.path)
14
+ restartWorkspaceSessions(workspace.path)
15
+ publishEvent({ type: 'env:updated', workspaceId: workspace.id })
16
+ }
@@ -45,6 +45,8 @@ async function loadModule(name: string): Promise<Record<string, unknown>> {
45
45
 
46
46
  const mod = (await import(filePath + `?t=${file.lastModified}`)) as Record<string, unknown>
47
47
  moduleCache.set(name, mod)
48
+ // Tell the parent what's cached here — introspection only, shown in /status.
49
+ send({ type: 'loaded', module: name })
48
50
  return mod
49
51
  }
50
52