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/server/cli.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env bun
2
2
  import './cli-colors' // must precede citty: sets NO_COLOR before its color flag is computed
3
3
  import { defineCommand, runMain, showUsage } from 'citty'
4
- import { existsSync } from 'node:fs'
4
+ import { existsSync, readFileSync } from 'node:fs'
5
5
  import { tmpdir } from 'node:os'
6
6
  import { join, resolve } from 'path'
7
7
  import pc from 'picocolors'
@@ -18,10 +18,18 @@ 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'
24
31
  import { liftToWorkspaceRoot, registerWorkspace } from './registry'
32
+ import { serverCwd } from './server-cwd'
25
33
  import {
26
34
  type SkillStatus,
27
35
  isBehind,
@@ -31,6 +39,12 @@ import {
31
39
  staleSkillNotice
32
40
  } from './skill-version'
33
41
  import { installBundledSkills } from './skills-template'
42
+ import {
43
+ getWorkspaceEnvView,
44
+ isValidEnvKey,
45
+ secretBackend,
46
+ updateWorkspaceEnv
47
+ } from './workspace-env'
34
48
  import { provisionWorkspace, skillsDirFor } from './workspace-init'
35
49
 
36
50
  // ---- helpers ----------------------------------------------------------------
@@ -85,20 +99,19 @@ async function openBrowser(url: string) {
85
99
  } catch {}
86
100
  }
87
101
 
88
- // Spawn the server as a child with cwd=projectRoot so bunfig.toml is found at Bun startup.
89
- // bunfig.toml is read before any JS runs, so process.chdir() is too late.
90
- // MOI_SERVER=1 tells the child it is the actual server process. No `--hot`:
91
- // frontend HMR comes from Bun.serve's dev bundler, and server reloads are a
92
- // full process restart driven by the dev supervisor (see runDevSupervisor).
102
+ // Spawn the server as a child. MOI_SERVER=1 tells the child it is the actual
103
+ // server process. No `--hot`: frontend HMR comes from Bun.serve's dev bundler,
104
+ // and server reloads are a full process restart driven by the dev supervisor
105
+ // (see runDevSupervisor).
93
106
  function spawnServer(
94
- projectRoot: string,
107
+ cwd: string,
95
108
  env: Record<string, string | undefined> = process.env
96
109
  ): ReturnType<typeof Bun.spawn> {
97
110
  return Bun.spawn(['bun', import.meta.filename, 'start'], {
98
111
  stdin: 'inherit',
99
112
  stdout: 'inherit',
100
113
  stderr: 'inherit',
101
- cwd: projectRoot,
114
+ cwd,
102
115
  env: { ...env, MOI_SERVER: '1' }
103
116
  })
104
117
  }
@@ -269,7 +282,7 @@ const init = defineCommand({
269
282
 
270
283
  if (!running && args.web) {
271
284
  console.log(pc.dim(' Starting server…'))
272
- const proc = spawnServer(projectRoot)
285
+ const proc = spawnServer(serverCwd(projectRoot, false))
273
286
  running = await waitForServer()
274
287
  if (!running) {
275
288
  console.error(pc.red(' Server failed to start\n'))
@@ -350,12 +363,14 @@ const start = defineCommand({
350
363
  await runDevSupervisor(projectRoot, env)
351
364
  return
352
365
  }
353
- const proc = spawnServer(projectRoot, env)
366
+ const proc = spawnServer(serverCwd(projectRoot, dev), env)
354
367
  await proc.exited
355
368
  process.exit(proc.exitCode ?? 0)
356
369
  }
357
370
 
358
- // This IS the server process (MOI_SERVER=1, cwd=projectRoot, bunfig.toml loaded).
371
+ // This IS the server process (MOI_SERVER=1). cwd is the package root when the
372
+ // dev bundler runs (bunfig loaded at Bun startup) or a neutral dir for a
373
+ // prebuilt install — see serverCwd().
359
374
  await import('./web')
360
375
  console.log(`\n${pc.green('✓')} Server started on http://localhost:${PORT}`)
361
376
  console.log(pc.dim(' Press Ctrl+C to stop\n'))
@@ -663,6 +678,164 @@ const status = defineCommand({
663
678
  }
664
679
  })
665
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
+
666
839
  // ---- openclaw subcommands ---------------------------------------------------
667
840
 
668
841
  // Match an `agent` argument against `agentId` (exact) or `name`
@@ -1511,9 +1684,49 @@ const skill = defineCommand({
1511
1684
  }
1512
1685
  })
1513
1686
 
1687
+ // `<package version> (<8-char commit>)`, e.g. `0.1.3 (27e17e80)`. The commit is
1688
+ // read from git at call time, so it appears for a source/`bun link` checkout and
1689
+ // is simply omitted for a published package (which ships no .git).
1690
+ function moiVersion(): string {
1691
+ const root = join(import.meta.dir, '..')
1692
+ let version = '0.0.0'
1693
+ try {
1694
+ version = (JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { version: string })
1695
+ .version
1696
+ } catch {}
1697
+ let commit = ''
1698
+ try {
1699
+ const out = Bun.spawnSync(['git', 'rev-parse', '--short=8', 'HEAD'], { cwd: root })
1700
+ if (out.success) commit = out.stdout.toString().trim()
1701
+ } catch {}
1702
+ return commit ? `${version} (${commit})` : version
1703
+ }
1704
+
1705
+ const version = defineCommand({
1706
+ meta: { name: 'version', description: 'Print the moi version' },
1707
+ run() {
1708
+ console.log(moiVersion())
1709
+ }
1710
+ })
1711
+
1514
1712
  const main = defineCommand({
1515
- meta: { name: 'moi', description: 'moi — local AI workspace' },
1516
- subCommands: { init, start, bundle, refresh, theme, config, status, openclaw, scratch, skill }
1713
+ // A function so the git lookup runs only for `moi --version` / `--help`, not on
1714
+ // every command. citty resolves a function meta (used for --version + usage).
1715
+ meta: () => ({ name: 'moi', description: 'moi — local AI workspace', version: moiVersion() }),
1716
+ subCommands: {
1717
+ init,
1718
+ start,
1719
+ bundle,
1720
+ refresh,
1721
+ theme,
1722
+ config,
1723
+ env,
1724
+ status,
1725
+ openclaw,
1726
+ scratch,
1727
+ skill,
1728
+ version
1729
+ }
1517
1730
  })
1518
1731
 
1519
1732
  // Route `moi config --help` to the same terse cheat sheet as `moi config help`;
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
 
@@ -16,6 +16,7 @@
16
16
  // are paths relative to it (`"widgets/hello"` → `.moi/widgets/hello.server.ts`).
17
17
  // This is the contract documented in the widgets SKILL.
18
18
  import { LRUCache } from 'lru-cache'
19
+ import { readFileSync } from 'node:fs'
19
20
  import { tmpdir } from 'node:os'
20
21
  import { join } from 'path'
21
22
 
@@ -38,6 +39,16 @@ type Slot = {
38
39
  readyPromise: Promise<void>
39
40
  pending: Map<string, Pending>
40
41
  killed: boolean
42
+ // Introspection only (surfaced by /status) — not load-bearing.
43
+ ready: boolean
44
+ spawnedAt: number
45
+ lastCallAt: number | null
46
+ calls: number
47
+ errors: number
48
+ timeouts: number
49
+ // Module keys the worker has loaded and cached (reported via 'loaded' IPC,
50
+ // pruned when reloadModules evicts them).
51
+ modules: Set<string>
41
52
  }
42
53
 
43
54
  function rejectAndClearPending(slot: Slot, reason: string) {
@@ -76,7 +87,14 @@ function spawnSlot(workspacePath: string, workspaceEnv: Record<string, string>):
76
87
  worker: undefined as never,
77
88
  readyPromise,
78
89
  pending: new Map(),
79
- killed: false
90
+ killed: false,
91
+ ready: false,
92
+ spawnedAt: Date.now(),
93
+ lastCallAt: null,
94
+ calls: 0,
95
+ errors: 0,
96
+ timeouts: 0,
97
+ modules: new Set()
80
98
  }
81
99
 
82
100
  slot.worker = Bun.spawn([process.execPath, WORKER_PATH], {
@@ -106,13 +124,25 @@ function spawnSlot(workspacePath: string, workspaceEnv: Record<string, string>):
106
124
  if (slots.peek(workspacePath) === slot) slots.delete(workspacePath)
107
125
  },
108
126
  ipc(message) {
109
- const msg = message as { type: string; id?: string; data?: string; message?: string }
127
+ const msg = message as {
128
+ type: string
129
+ id?: string
130
+ data?: string
131
+ message?: string
132
+ module?: string
133
+ }
110
134
 
111
135
  if (msg.type === 'ready') {
136
+ slot.ready = true
112
137
  readyResolve()
113
138
  return
114
139
  }
115
140
 
141
+ if (msg.type === 'loaded' && msg.module) {
142
+ slot.modules.add(msg.module)
143
+ return
144
+ }
145
+
116
146
  if (msg.id) {
117
147
  const p = slot.pending.get(msg.id)
118
148
  if (!p) return
@@ -122,6 +152,7 @@ function spawnSlot(workspacePath: string, workspaceEnv: Record<string, string>):
122
152
  if (msg.type === 'result') {
123
153
  p.resolve(msg.data!)
124
154
  } else if (msg.type === 'error') {
155
+ slot.errors++
125
156
  p.reject(new Error(msg.message ?? 'Unknown error'))
126
157
  }
127
158
  }
@@ -165,14 +196,18 @@ export async function callFunction(
165
196
  // up current .env + custom overrides. Env is fixed at spawn — an already-warm
166
197
  // worker keeps its snapshot until restartWorker() reaps it. Widgets only see
167
198
  // secrets scoped to the 'widgets' sink.
168
- const workspaceEnv = await resolveWorkspaceEnv(workspacePath, 'widgets')
199
+ const workspaceEnv = await resolveWorkspaceEnv(workspacePath)
169
200
  const slot = getOrSpawn(workspacePath, workspaceEnv)
170
201
  await slot.readyPromise
171
202
 
203
+ slot.calls++
204
+ slot.lastCallAt = Date.now()
205
+
172
206
  const id = crypto.randomUUID()
173
207
  return new Promise((resolve, reject) => {
174
208
  const timer = setTimeout(() => {
175
209
  slot.pending.delete(id)
210
+ slot.timeouts++
176
211
  reject(new Error(`Function call timed out: ${module}/${name}`))
177
212
  }, CALL_TIMEOUT_MS)
178
213
 
@@ -206,6 +241,66 @@ export function restartWorker(workspacePath: string) {
206
241
  slots.delete(workspacePath)
207
242
  }
208
243
 
244
+ // Caps surfaced in /status so the numbers there are self-explanatory.
245
+ export const WORKER_LIMITS = {
246
+ maxWorkers: MAX_WORKERS,
247
+ idleTtlMs: WORKER_IDLE_TTL_MS,
248
+ callTimeoutMs: CALL_TIMEOUT_MS
249
+ } as const
250
+
251
+ export type WorkerDebugInfo = {
252
+ workspacePath: string
253
+ pid: number | undefined
254
+ ready: boolean
255
+ spawnedAt: number
256
+ lastCallAt: number | null
257
+ calls: number
258
+ errors: number
259
+ timeouts: number
260
+ pending: number
261
+ // ms until the LRU idle TTL reaps this worker (refreshed on every call)
262
+ ttlRemainingMs: number
263
+ // Resident memory of the worker process; null when /proc isn't available (macOS)
264
+ rssBytes: number | null
265
+ modules: string[]
266
+ }
267
+
268
+ // Best-effort RSS from /proc — Linux only, returns null elsewhere. VmRSS is in
269
+ // kB, so no page-size assumptions. Sync read of a tiny procfs file is cheap.
270
+ function readRss(pid: number | undefined): number | null {
271
+ if (!pid || process.platform !== 'linux') return null
272
+ try {
273
+ const m = readFileSync(`/proc/${pid}/status`, 'utf8').match(/^VmRSS:\s+(\d+)\s+kB/m)
274
+ return m ? Number(m[1]) * 1024 : null
275
+ } catch {
276
+ return null
277
+ }
278
+ }
279
+
280
+ // A snapshot of the live worker pool, for the /status page. Iteration and
281
+ // getRemainingTTL don't refresh LRU recency, so peeking is side-effect free.
282
+ export function getWorkersDebugSnapshot(): WorkerDebugInfo[] {
283
+ const out: WorkerDebugInfo[] = []
284
+ for (const [workspacePath, slot] of slots.entries()) {
285
+ if (slot.killed) continue
286
+ out.push({
287
+ workspacePath,
288
+ pid: slot.worker.pid,
289
+ ready: slot.ready,
290
+ spawnedAt: slot.spawnedAt,
291
+ lastCallAt: slot.lastCallAt,
292
+ calls: slot.calls,
293
+ errors: slot.errors,
294
+ timeouts: slot.timeouts,
295
+ pending: slot.pending.size,
296
+ ttlRemainingMs: slots.getRemainingTTL(workspacePath),
297
+ rssBytes: readRss(slot.worker.pid),
298
+ modules: [...slot.modules].sort()
299
+ })
300
+ }
301
+ return out
302
+ }
303
+
209
304
  export function reloadModules(modules: string[], workspacePath: string) {
210
305
  if (modules.length === 0) return
211
306
  // peek: don't refresh TTL just because files changed. If the worker was
@@ -214,5 +309,8 @@ export function reloadModules(modules: string[], workspacePath: string) {
214
309
  if (!slot || slot.killed) return
215
310
  try {
216
311
  slot.worker.send({ type: 'reload', modules })
312
+ // The worker evicts these from its module cache; it re-reports 'loaded'
313
+ // on the next call, so drop them from the introspection set too.
314
+ for (const m of modules) slot.modules.delete(m)
217
315
  } catch {}
218
316
  }
@@ -1,10 +1,10 @@
1
- import envPaths from 'env-paths'
2
1
  import { mkdir } from 'node:fs/promises'
3
2
  import { homedir } from 'node:os'
4
3
  import { join, resolve, sep } from 'path'
5
4
 
6
5
  import type { DiscoveredWorkspace, WorkspaceEntry, WorkspaceType } from '@/lib/types'
7
6
 
7
+ import { DATA_DIR } from './data-dir'
8
8
  import { type OpenClawAgent, discoverOpenClawAgents } from './openclaw'
9
9
 
10
10
  // Replace the home-dir prefix with `~` for display. Keeps the original
@@ -22,7 +22,6 @@ function withDisplayPath<T extends { path: string }>(entry: T): T & { displayPat
22
22
  return { ...entry, displayPath: tildify(entry.path) }
23
23
  }
24
24
 
25
- const DATA_DIR = envPaths('moi', { suffix: false }).data
26
25
  export const DEFAULT_REGISTRY_PATH = join(DATA_DIR, 'workspaces.json')
27
26
 
28
27
  // Overridable for tests
@@ -0,0 +1,19 @@
1
+ // The env "required" view aggregates `config.requiredEnv` declared by both
2
+ // widgets and views, each key mapped to the bundle ids that asked for it.
3
+ // Shared by the env API (api.ts) and the `moi env` CLI (cli-env.ts).
4
+ import { collectViewRequiredEnv } from './views'
5
+ import { collectRequiredEnv } from './widgets'
6
+
7
+ export async function requiredEnvFor(workspacePath: string): Promise<Record<string, string[]>> {
8
+ const [widgets, views] = await Promise.all([
9
+ collectRequiredEnv(workspacePath),
10
+ collectViewRequiredEnv(workspacePath)
11
+ ])
12
+ const out: Record<string, string[]> = {}
13
+ for (const map of [widgets, views]) {
14
+ for (const [key, ids] of Object.entries(map)) {
15
+ out[key] = [...(out[key] ?? []), ...ids]
16
+ }
17
+ }
18
+ return out
19
+ }
@@ -19,10 +19,22 @@ import {
19
19
  toRichText
20
20
  } from 'tldraw'
21
21
 
22
- import type { ScratchImageQuality, ScratchOp, ScratchOpResult, ScratchStyle } from '@/lib/types'
22
+ import { describeNewerWriter, sequencesAhead } from '@/lib/scratchpad-skew'
23
+ import type {
24
+ ScratchImageQuality,
25
+ ScratchOp,
26
+ ScratchOpResult,
27
+ ScratchStyle,
28
+ ScratchpadWriter
29
+ } from '@/lib/types'
23
30
 
24
31
  import { publishEvent } from './events'
25
- import { type ScratchpadDoc, loadScratchpadDoc, saveScratchpadDoc } from './scratchpad'
32
+ import {
33
+ SCRATCHPAD_WRITER,
34
+ type ScratchpadDoc,
35
+ loadScratchpadDoc,
36
+ saveScratchpadDoc
37
+ } from './scratchpad'
26
38
 
27
39
  // Server-side Scratchpad writer. The browser is no longer required to draw: we run
28
40
  // the same ops against a *headless* tldraw store here, persist the snapshot, and
@@ -65,10 +77,31 @@ function styleProps(style: ScratchStyle): Record<string, unknown> {
65
77
 
66
78
  // A fresh headless store hydrated from the saved snapshot (or empty). The
67
79
  // snapshot shape (`{ document }`) matches what the browser PUTs and loads.
68
- function buildStore(doc: ScratchpadDoc | null): TLStore {
80
+ // A failed load is inspected for version skew: tldraw has no down-migrations,
81
+ // so a snapshot written by a newer tldraw is unreadable here — but intact.
82
+ // That gets a loud, actionable error instead of tldraw's bare `migration-error`
83
+ // (which surfaces verbatim through the control port to the `moi scratch` CLI).
84
+ function buildStore(doc: ScratchpadDoc | null, writer: ScratchpadWriter | undefined): TLStore {
69
85
  const store = createTLStore({ shapeUtils: defaultShapeUtils, bindingUtils: defaultBindingUtils })
70
86
  if (doc?.store) {
71
- loadSnapshot(store, { document: doc } as unknown as Parameters<typeof loadSnapshot>[1])
87
+ try {
88
+ loadSnapshot(store, { document: doc } as unknown as Parameters<typeof loadSnapshot>[1])
89
+ } catch (err) {
90
+ const ahead = sequencesAhead(doc.schema, store.schema.serialize().sequences)
91
+ if (ahead.length > 0) {
92
+ throw new Error(
93
+ `Scratchpad was written by a newer moi (${describeNewerWriter(writer, ahead)}); ` +
94
+ `this server has tldraw ${SCRATCHPAD_WRITER.tldraw}. Restart the newer server or ` +
95
+ `update this install (bun install -g moi-computer@latest). ` +
96
+ `The canvas file is intact — do not reset it.`
97
+ )
98
+ }
99
+ // Not skew — the snapshot itself is bad. Keep the original cause visible.
100
+ throw new Error(
101
+ `Scratchpad snapshot failed to load (not a version mismatch — the file may be ` +
102
+ `corrupted): ${err instanceof Error ? err.message : String(err)}`
103
+ )
104
+ }
72
105
  }
73
106
  // Seed the document/page records a fresh (or partial) store needs to be valid.
74
107
  store.ensureStoreIsUsable()
@@ -368,8 +401,8 @@ export function executeScratchOp(
368
401
  op: ScratchOp
369
402
  ): Promise<ScratchOpResult> {
370
403
  return withLock(workspacePath, async () => {
371
- const { document } = await loadScratchpadDoc(workspacePath)
372
- const store = buildStore(document)
404
+ const { document, writer } = await loadScratchpadDoc(workspacePath)
405
+ const store = buildStore(document, writer)
373
406
  // add-image decodes/resizes the file first, so it's the one async op.
374
407
  const result = op.kind === 'add-image' ? await applyAddImage(store, op) : applyOp(store, op)
375
408
  const next = getSnapshot(store).document as unknown as ScratchpadDoc