moi-computer 0.1.4 → 0.3.0-next.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/README.md +26 -52
- package/client/api/workspaces.ts +3 -5
- package/client/components/Scratchpad.tsx +169 -9
- package/client/components/layout/SidebarLayout.tsx +1 -12
- package/client/components/settings/SettingsPages.tsx +8 -60
- package/client/components/tool-group/fixtures.ts +60 -66
- package/client/hooks/useEnvVars.ts +20 -0
- package/client/hooks/useMeiEvents.ts +2 -0
- package/dist/chunk-07qf2tv1.css +1 -0
- package/dist/chunk-c3zjp9ez.js +672 -0
- package/dist/index.html +1 -1
- package/lib/scratchpad-skew.ts +64 -0
- package/lib/types.ts +5 -7
- package/package.json +3 -3
- package/server/api.ts +53 -54
- package/server/cc-session.ts +1 -1
- package/server/cli-colors.ts +6 -3
- package/server/cli-env.ts +237 -0
- package/server/cli-pc.ts +20 -0
- package/server/cli.ts +182 -3
- package/server/control.ts +11 -0
- package/server/data-dir.ts +9 -0
- package/server/env-apply.ts +16 -0
- package/server/functions-worker.ts +2 -0
- package/server/functions.ts +101 -3
- package/server/registry.ts +1 -2
- package/server/required-env.ts +19 -0
- package/server/scratchpad-assets.ts +223 -0
- package/server/scratchpad-executor.ts +88 -23
- package/server/scratchpad.ts +110 -20
- package/server/status.ts +54 -3
- package/server/thread-config.ts +2 -3
- package/server/vendor.ts +15 -8
- package/server/workspace-env.ts +69 -80
- package/workspace/.claude/skills/moi-workspace/SCRATCHPAD.md +5 -3
- package/workspace/.claude/skills/moi-workspace/SKILL.md +40 -6
- package/dist/chunk-kc6e9nd4.css +0 -1
- package/dist/chunk-yf3p7qg7.js +0 -673
- /package/client/{CLAUDE.md → AGENTS.md} +0 -0
- /package/server/{CLAUDE.md → AGENTS.md} +0 -0
package/dist/index.html
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
}
|
|
22
22
|
</script>
|
|
23
23
|
|
|
24
|
-
<link rel="stylesheet" crossorigin href="/chunk-
|
|
24
|
+
<link rel="stylesheet" crossorigin href="/chunk-07qf2tv1.css"><script type="module" crossorigin src="/chunk-c3zjp9ez.js"></script></head>
|
|
25
25
|
<body>
|
|
26
26
|
<div id="root"></div>
|
|
27
27
|
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { ScratchpadWriter } from './types'
|
|
2
|
+
|
|
3
|
+
// Version-skew detection for Scratchpad snapshots. A tldraw snapshot embeds the
|
|
4
|
+
// serialized schema of whatever tldraw *wrote* it, and tldraw has no
|
|
5
|
+
// down-migrations — a snapshot written by a newer schema can never be loaded by
|
|
6
|
+
// an older one. When `loadSnapshot`/`migrateStoreSnapshot` fails, these helpers
|
|
7
|
+
// tell "the file is from a newer tldraw" apart from genuine corruption, so both
|
|
8
|
+
// the server error (scratchpad-executor.ts) and the client notice
|
|
9
|
+
// (client/components/Scratchpad.tsx) can say something actionable instead of
|
|
10
|
+
// tldraw's bare `migration-error`. See docs/moi-scratchpad.md § Version skew.
|
|
11
|
+
|
|
12
|
+
// A serialized tldraw schema's migration sequences: sequence id → version, e.g.
|
|
13
|
+
// `{ "com.tldraw.shape.note": 9 }`.
|
|
14
|
+
export type SchemaSequences = Record<string, number>
|
|
15
|
+
|
|
16
|
+
// One sequence in the file that the runtime can't load: the file's version is
|
|
17
|
+
// ahead of the runtime's, or the runtime doesn't know the sequence at all
|
|
18
|
+
// (which also means a newer writer).
|
|
19
|
+
export type SequenceAhead = { id: string; fileVersion: number; runtimeVersion?: number }
|
|
20
|
+
|
|
21
|
+
// Pull the `sequences` map out of an unknown `document.schema` value —
|
|
22
|
+
// best-effort, since the file is disk JSON. Returns null when the shape isn't a
|
|
23
|
+
// v2 serialized schema.
|
|
24
|
+
export function schemaSequences(schema: unknown): SchemaSequences | null {
|
|
25
|
+
if (!schema || typeof schema !== 'object') return null
|
|
26
|
+
const sequences = (schema as { sequences?: unknown }).sequences
|
|
27
|
+
if (!sequences || typeof sequences !== 'object') return null
|
|
28
|
+
const out: SchemaSequences = {}
|
|
29
|
+
for (const [id, version] of Object.entries(sequences)) {
|
|
30
|
+
if (typeof version === 'number') out[id] = version
|
|
31
|
+
}
|
|
32
|
+
return Object.keys(out).length > 0 ? out : null
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// The file sequences the runtime is behind on. Non-empty means the snapshot was
|
|
36
|
+
// written by a newer tldraw than the runtime — the load failure is skew, not
|
|
37
|
+
// corruption.
|
|
38
|
+
export function sequencesAhead(fileSchema: unknown, runtime: SchemaSequences): SequenceAhead[] {
|
|
39
|
+
const file = schemaSequences(fileSchema)
|
|
40
|
+
if (!file) return []
|
|
41
|
+
const ahead: SequenceAhead[] = []
|
|
42
|
+
for (const [id, fileVersion] of Object.entries(file)) {
|
|
43
|
+
const runtimeVersion = runtime[id]
|
|
44
|
+
if (runtimeVersion === undefined) ahead.push({ id, fileVersion })
|
|
45
|
+
else if (fileVersion > runtimeVersion) ahead.push({ id, fileVersion, runtimeVersion })
|
|
46
|
+
}
|
|
47
|
+
return ahead
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// "moi 0.1.5, tldraw 5.3.0" when the stamp is there, else the sequences that
|
|
51
|
+
// are ahead — so the message can always name *what* is newer.
|
|
52
|
+
export function describeNewerWriter(
|
|
53
|
+
writer: ScratchpadWriter | undefined,
|
|
54
|
+
ahead: SequenceAhead[]
|
|
55
|
+
): string {
|
|
56
|
+
if (writer) return `moi ${writer.moi}, tldraw ${writer.tldraw}`
|
|
57
|
+
return ahead
|
|
58
|
+
.map(a =>
|
|
59
|
+
a.runtimeVersion === undefined
|
|
60
|
+
? `${a.id} v${a.fileVersion} (unknown here)`
|
|
61
|
+
: `${a.id} v${a.fileVersion} > v${a.runtimeVersion}`
|
|
62
|
+
)
|
|
63
|
+
.join(', ')
|
|
64
|
+
}
|
package/lib/types.ts
CHANGED
|
@@ -106,6 +106,11 @@ export type ScratchOp =
|
|
|
106
106
|
// data URL for `view`, or a bare ack for mutations.
|
|
107
107
|
export type ScratchOpResult = { name: string } | { image: string } | { ok: true }
|
|
108
108
|
|
|
109
|
+
// The process that last persisted `.moi/.scratchpad.json` (always the server —
|
|
110
|
+
// browser saves funnel through it). Stamped on save so an older reader hitting
|
|
111
|
+
// the snapshot can name the version it needs (see lib/scratchpad-skew.ts).
|
|
112
|
+
export type ScratchpadWriter = { moi: string; tldraw: string }
|
|
113
|
+
|
|
109
114
|
// An attachment uploaded ahead of a chat message. The bytes live server-side in
|
|
110
115
|
// an in-memory upload store (see server/uploads.ts); a chat frame references it
|
|
111
116
|
// by `id`. `kind` splits the two delivery paths: an `image` is inlined as a
|
|
@@ -386,11 +391,6 @@ export type WorkspacePreview = {
|
|
|
386
391
|
items: { x: number; y: number; w: number; h: number }[]
|
|
387
392
|
}
|
|
388
393
|
|
|
389
|
-
// Where a custom secret is allowed to flow: the widget function workers, the
|
|
390
|
-
// agent's Bash, or both. Lets a key meant for a widget stay out of the agent's
|
|
391
|
-
// (bypass-permissions) environment, and vice versa.
|
|
392
|
-
export type EnvScope = 'widgets' | 'agent' | 'both'
|
|
393
|
-
|
|
394
394
|
// One effective env var, as surfaced by GET /api/workspaces/:id/env. Values are
|
|
395
395
|
// NEVER returned — the API masks both `.env` and custom secrets, so editing is
|
|
396
396
|
// write-only. Presence in the list (with `source`) is all the UI needs.
|
|
@@ -399,8 +399,6 @@ export type WorkspaceEnvVar = {
|
|
|
399
399
|
// `dotenv`: only from a `.env` file. `custom`: only a UI-managed secret.
|
|
400
400
|
// `both`: a custom secret shadowing a `.env` value (custom wins).
|
|
401
401
|
source: 'dotenv' | 'custom' | 'both'
|
|
402
|
-
// Sink scope — present for custom/both (UI-managed) keys.
|
|
403
|
-
scope?: EnvScope
|
|
404
402
|
// The `.env` files that declare this key (when dotenv-sourced).
|
|
405
403
|
files?: string[]
|
|
406
404
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "moi-computer",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0-next.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": "
|
|
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 {
|
|
18
|
-
import { callFunction, parseFunctionPath
|
|
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'
|
|
@@ -32,48 +26,29 @@ import {
|
|
|
32
26
|
tildify
|
|
33
27
|
} from './registry'
|
|
34
28
|
import { loadScratchpadDoc, saveScratchpadDoc } from './scratchpad'
|
|
29
|
+
import { MAX_ASSET_BYTES, scratchpadAssetFile, storeScratchpadAsset } from './scratchpad-assets'
|
|
35
30
|
import { DIST_DIR, prebuilt } from './static'
|
|
36
31
|
import { getSessionEvents, getSessions } from './state'
|
|
37
32
|
import { getThreadConfig, saveThreadConfig } from './thread-config'
|
|
38
33
|
import type { ThreadConfigPatch } from './thread-config'
|
|
39
34
|
import { serveWorkspaceImagePreview } from './preview'
|
|
40
35
|
import { MAX_UPLOAD_BYTES, addUpload, getUpload } from './uploads'
|
|
41
|
-
import {
|
|
42
|
-
import {
|
|
36
|
+
import { requiredEnvFor } from './required-env'
|
|
37
|
+
import { listViews, serveView } from './views'
|
|
38
|
+
import { listWidgets, serveWidget } from './widgets'
|
|
43
39
|
import { getWorkspaceConfig, setWorkspaceConfig } from './workspace-config'
|
|
44
40
|
import {
|
|
45
41
|
CREATED_WORKSPACES_ROOT,
|
|
46
42
|
provisionWorkspace,
|
|
47
43
|
validateWorkspaceFolderName
|
|
48
44
|
} from './workspace-init'
|
|
49
|
-
import {
|
|
50
|
-
getWorkspaceEnvView,
|
|
51
|
-
isValidEnvKey,
|
|
52
|
-
isValidScope,
|
|
53
|
-
updateWorkspaceEnv
|
|
54
|
-
} from './workspace-env'
|
|
45
|
+
import { getWorkspaceEnvView, isValidEnvKey, updateWorkspaceEnv } from './workspace-env'
|
|
55
46
|
import type { EnvUpdate } from './workspace-env'
|
|
56
47
|
|
|
57
48
|
// The resolved workspace is stashed on the context by `withWorkspace`, so every
|
|
58
49
|
// `/api/workspaces/:id/*` handler can read it without re-querying the registry.
|
|
59
50
|
type ApiEnv = { Variables: { ws: WorkspaceEntry } }
|
|
60
51
|
|
|
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
52
|
async function handleFunctionCall(
|
|
78
53
|
req: Request,
|
|
79
54
|
tail: string,
|
|
@@ -303,11 +278,12 @@ one.get('/mcp', async c => {
|
|
|
303
278
|
// custom secrets + scopes + declared-required keys; values masked).
|
|
304
279
|
one.get('/env', async c => {
|
|
305
280
|
const ws = c.get('ws')
|
|
306
|
-
|
|
307
|
-
|
|
281
|
+
// Unawaited on purpose: getWorkspaceEnvView loads it in parallel with the
|
|
282
|
+
// env stores (manifest reads and env reads are independent).
|
|
283
|
+
return c.json(await getWorkspaceEnvView(ws.path, requiredEnvFor(ws.path)))
|
|
308
284
|
})
|
|
309
285
|
|
|
310
|
-
// PUT patches custom secrets (set/remove
|
|
286
|
+
// PUT patches custom secrets (set/remove) and/or the inheritDotenv mode,
|
|
311
287
|
// then reaps the workspace's function worker and idle agent sessions so the next
|
|
312
288
|
// call/message picks up the change (env is frozen at spawn — a hard restart is
|
|
313
289
|
// the only way).
|
|
@@ -336,15 +312,6 @@ one.put('/env', async c => {
|
|
|
336
312
|
}
|
|
337
313
|
patch.remove = body.remove as string[]
|
|
338
314
|
}
|
|
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
315
|
if (body.inheritDotenv !== undefined) {
|
|
349
316
|
if (typeof body.inheritDotenv !== 'boolean') {
|
|
350
317
|
return c.text('inheritDotenv must be a boolean', 400)
|
|
@@ -355,19 +322,14 @@ one.put('/env', async c => {
|
|
|
355
322
|
// Skip the write + reaps for a no-op PUT (no recognized fields) so an empty
|
|
356
323
|
// body doesn't needlessly kill warm workers / idle sessions.
|
|
357
324
|
const hasChange =
|
|
358
|
-
patch.set !== undefined ||
|
|
359
|
-
patch.remove !== undefined ||
|
|
360
|
-
patch.scopes !== undefined ||
|
|
361
|
-
patch.inheritDotenv !== undefined
|
|
325
|
+
patch.set !== undefined || patch.remove !== undefined || patch.inheritDotenv !== undefined
|
|
362
326
|
if (hasChange) {
|
|
363
327
|
await updateWorkspaceEnv(ws.path, patch)
|
|
364
|
-
// Frozen-at-spawn: reap workers/idle sessions
|
|
365
|
-
|
|
366
|
-
restartWorkspaceSessions(ws.path)
|
|
328
|
+
// Frozen-at-spawn: reap workers/idle sessions and tell other clients.
|
|
329
|
+
applyEnvChanged(ws)
|
|
367
330
|
}
|
|
368
331
|
|
|
369
|
-
|
|
370
|
-
return c.json(await getWorkspaceEnvView(ws.path, required))
|
|
332
|
+
return c.json(await getWorkspaceEnvView(ws.path, requiredEnvFor(ws.path)))
|
|
371
333
|
})
|
|
372
334
|
|
|
373
335
|
// Models the workspace's agent backend can run, normalized across providers.
|
|
@@ -428,6 +390,43 @@ one.put('/scratchpad', async c => {
|
|
|
428
390
|
return c.body(null, 204)
|
|
429
391
|
})
|
|
430
392
|
|
|
393
|
+
// Scratchpad assets: pasted/dropped image bytes live as content-addressed files
|
|
394
|
+
// in `.moi/.scratchpad/`, referenced from the snapshot by `asset:` srcs —
|
|
395
|
+
// never inlined as base64 in the JSON (see server/scratchpad-assets.ts). The
|
|
396
|
+
// browser's TLAssetStore POSTs the raw file here on paste and resolves `asset:`
|
|
397
|
+
// srcs back through the GET when rendering.
|
|
398
|
+
one.post('/scratchpad/assets', async c => {
|
|
399
|
+
const length = Number(c.req.header('content-length') ?? 0)
|
|
400
|
+
if (length > MAX_ASSET_BYTES) {
|
|
401
|
+
return c.text(`Asset too large (max ${MAX_ASSET_BYTES / (1024 * 1024)} MB)`, 413)
|
|
402
|
+
}
|
|
403
|
+
const bytes = new Uint8Array(await c.req.arrayBuffer())
|
|
404
|
+
if (bytes.length === 0) return c.text('Empty body', 400)
|
|
405
|
+
if (bytes.length > MAX_ASSET_BYTES) {
|
|
406
|
+
return c.text(`Asset too large (max ${MAX_ASSET_BYTES / (1024 * 1024)} MB)`, 413)
|
|
407
|
+
}
|
|
408
|
+
const mimeType = c.req.header('content-type') ?? 'application/octet-stream'
|
|
409
|
+
return c.json(await storeScratchpadAsset(c.get('ws').path, bytes, mimeType))
|
|
410
|
+
})
|
|
411
|
+
|
|
412
|
+
// The file name is content-addressed (sha256 of the bytes), so a hit is
|
|
413
|
+
// immutable — let the browser cache it indefinitely.
|
|
414
|
+
one.get('/scratchpad/assets/:file', async c => {
|
|
415
|
+
const resolved = scratchpadAssetFile(c.get('ws').path, c.req.param('file'))
|
|
416
|
+
if (!resolved || !(await resolved.file.exists())) return c.text('Not found', 404)
|
|
417
|
+
return new Response(resolved.file, {
|
|
418
|
+
headers: {
|
|
419
|
+
'Content-Type': resolved.mimeType,
|
|
420
|
+
'Cache-Control': 'public, max-age=31536000, immutable',
|
|
421
|
+
// Assets are only ever consumed via <img>/<video>/fetch (which all ignore
|
|
422
|
+
// this), so force a download on direct navigation and block MIME sniffing:
|
|
423
|
+
// a pasted/uploaded SVG must not execute as script in the app origin.
|
|
424
|
+
'Content-Disposition': 'attachment',
|
|
425
|
+
'X-Content-Type-Options': 'nosniff'
|
|
426
|
+
}
|
|
427
|
+
})
|
|
428
|
+
})
|
|
429
|
+
|
|
431
430
|
// Workspace icon. PUT a raw image body (png/jpg/gif/webp) — the server resizes
|
|
432
431
|
// it to a 128×128 transparent WebP and stores it as base64. DELETE resets to the
|
|
433
432
|
// provider default. Both broadcast for a live refresh.
|
package/server/cc-session.ts
CHANGED
|
@@ -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
|
|
537
|
+
workspaceEnv: await resolveWorkspaceEnv(input.workspacePath)
|
|
538
538
|
})
|
|
539
539
|
}
|
|
540
540
|
|
package/server/cli-colors.ts
CHANGED
|
@@ -8,9 +8,12 @@
|
|
|
8
8
|
// module is imported *first* in `cli.ts` so it runs before citty's module is
|
|
9
9
|
// evaluated (citty computes its `noColor` flag once, at import time).
|
|
10
10
|
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
11
|
+
// This only closes citty's gap. Our own coloring goes through `cli-pc.ts`,
|
|
12
|
+
// which computes enablement directly (picocolors' auto-detection enables color
|
|
13
|
+
// on `CI` even through a pipe, and Bun evaluates picocolors too early for this
|
|
14
|
+
// `NO_COLOR` mutation to reach it). `FORCE_COLOR` and an explicit `NO_COLOR`
|
|
15
|
+
// are honored: if the user opted in or out of color, we leave their choice
|
|
16
|
+
// untouched.
|
|
14
17
|
|
|
15
18
|
if (!process.stdout.isTTY && !process.env.FORCE_COLOR && process.env.NO_COLOR == null) {
|
|
16
19
|
process.env.NO_COLOR = '1'
|
|
@@ -0,0 +1,237 @@
|
|
|
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 type { WorkspaceEntry, WorkspaceEnvView } from '@/lib/types'
|
|
9
|
+
|
|
10
|
+
import pc from './cli-pc'
|
|
11
|
+
import { columns } from './cli-ui'
|
|
12
|
+
import { CONTROL_PORT } from './constants'
|
|
13
|
+
import { findWorkspaceForPath, listWorkspaces } from './registry'
|
|
14
|
+
import { discoverDotenvKeys, resolveWorkspaceEnv } from './workspace-env'
|
|
15
|
+
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
// Workspace resolution: cwd → nearest registered workspace
|
|
18
|
+
// ---------------------------------------------------------------------------
|
|
19
|
+
|
|
20
|
+
// Every `moi env` subcommand targets the workspace containing cwd (same
|
|
21
|
+
// semantics as the control server's resolveWorkspace — works from `.moi/` or
|
|
22
|
+
// any subdirectory). Exits with a hint when cwd is outside every workspace, so
|
|
23
|
+
// a typo never creates an orphan env entry keyed to a phantom path.
|
|
24
|
+
export async function resolveCwdWorkspace(): Promise<WorkspaceEntry> {
|
|
25
|
+
const match = findWorkspaceForPath(await listWorkspaces(), process.cwd())
|
|
26
|
+
if (!match) {
|
|
27
|
+
console.error(
|
|
28
|
+
'\n' +
|
|
29
|
+
pc.red('✗') +
|
|
30
|
+
` ${process.cwd()} is not inside a registered moi workspace.\n` +
|
|
31
|
+
pc.dim(' Open it in moi, or run from the workspace root.\n')
|
|
32
|
+
)
|
|
33
|
+
process.exit(1)
|
|
34
|
+
}
|
|
35
|
+
return match
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// ---------------------------------------------------------------------------
|
|
39
|
+
// `moi env` rendering
|
|
40
|
+
// ---------------------------------------------------------------------------
|
|
41
|
+
|
|
42
|
+
function renderDotenvSection(view: WorkspaceEnvView): string[] {
|
|
43
|
+
const out: string[] = []
|
|
44
|
+
const state = view.inheritDotenv
|
|
45
|
+
? pc.dim('inherited: on')
|
|
46
|
+
: pc.yellow('inherited: off') + pc.dim(' (disabled in settings — keys not injected)')
|
|
47
|
+
out.push(`${pc.bold('.env files')} ${state}`)
|
|
48
|
+
if (view.files.length === 0) {
|
|
49
|
+
out.push(pc.dim(' none detected'))
|
|
50
|
+
} else {
|
|
51
|
+
const width = Math.max(...view.files.map(f => f.file.length))
|
|
52
|
+
for (const f of view.files) {
|
|
53
|
+
out.push(
|
|
54
|
+
` ${f.file.padEnd(width)} ${pc.dim(`${f.count} ${f.count === 1 ? 'key' : 'keys'}`)}`
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return out
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function sourceLabel(v: WorkspaceEnvView['vars'][number]): string {
|
|
62
|
+
// A dotenv-sourced key names its file(s); `both` is a custom secret shadowing
|
|
63
|
+
// a `.env` value (custom wins).
|
|
64
|
+
if (v.source === 'custom') return 'custom'
|
|
65
|
+
const files = (v.files ?? []).join(', ')
|
|
66
|
+
return v.source === 'both' ? `custom ${pc.dim(`(overrides ${files})`)}` : files
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// The full diagnostic view: vars with sources, dotenv state (files listed even
|
|
70
|
+
// when disabled), required-key satisfaction, and the secret backend. No values.
|
|
71
|
+
export function renderEnvView(entry: WorkspaceEntry, view: WorkspaceEnvView): string {
|
|
72
|
+
const lines: string[] = []
|
|
73
|
+
const name = entry.name ? ` (${entry.name})` : ''
|
|
74
|
+
lines.push(`${pc.bold('Workspace:')} ${entry.displayPath ?? entry.path}${pc.dim(name)}`)
|
|
75
|
+
lines.push('')
|
|
76
|
+
lines.push(...renderDotenvSection(view))
|
|
77
|
+
lines.push('')
|
|
78
|
+
|
|
79
|
+
if (view.vars.length === 0) {
|
|
80
|
+
lines.push(pc.dim('No env vars — add secrets in the workspace env settings, or create a .env.'))
|
|
81
|
+
} else {
|
|
82
|
+
lines.push(
|
|
83
|
+
columns(
|
|
84
|
+
['KEY', 'SOURCE'].map(h => pc.dim(h)),
|
|
85
|
+
view.vars.map(v => [v.key, sourceLabel(v)]),
|
|
86
|
+
''
|
|
87
|
+
)
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (view.required.length > 0) {
|
|
92
|
+
lines.push('')
|
|
93
|
+
lines.push(pc.bold('Required by widgets/views'))
|
|
94
|
+
const width = Math.max(...view.required.map(r => r.key.length))
|
|
95
|
+
for (const r of view.required) {
|
|
96
|
+
const mark = r.satisfied ? pc.green('✓') : pc.red('✗')
|
|
97
|
+
const who = r.widgets.join(', ')
|
|
98
|
+
lines.push(
|
|
99
|
+
r.satisfied
|
|
100
|
+
? ` ${mark} ${r.key.padEnd(width)} ${pc.dim(who)}`
|
|
101
|
+
: ` ${mark} ${r.key.padEnd(width)} missing — required by ${who}`
|
|
102
|
+
)
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
lines.push('')
|
|
107
|
+
lines.push(
|
|
108
|
+
pc.dim(`Secrets stored in: ${view.backend === 'keychain' ? 'OS keychain' : 'file (0600)'}`)
|
|
109
|
+
)
|
|
110
|
+
return lines.join('\n')
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ---------------------------------------------------------------------------
|
|
114
|
+
// `moi env set` value input
|
|
115
|
+
// ---------------------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
// Read a secret from a TTY without echoing: raw mode, chars collected until
|
|
118
|
+
// Enter, backspace honored, Ctrl-C aborts. The prompt goes to stderr so even a
|
|
119
|
+
// redirected stdout captures no trace of the interaction.
|
|
120
|
+
function readSecretFromTty(promptText: string): Promise<string> {
|
|
121
|
+
process.stderr.write(promptText)
|
|
122
|
+
const stdin = process.stdin
|
|
123
|
+
stdin.setRawMode(true)
|
|
124
|
+
stdin.resume()
|
|
125
|
+
let value = ''
|
|
126
|
+
return new Promise((resolve, reject) => {
|
|
127
|
+
const cleanup = () => {
|
|
128
|
+
stdin.setRawMode(false)
|
|
129
|
+
stdin.pause()
|
|
130
|
+
stdin.off('data', onData)
|
|
131
|
+
process.stderr.write('\n')
|
|
132
|
+
}
|
|
133
|
+
const onData = (chunk: Buffer) => {
|
|
134
|
+
for (const ch of chunk.toString('utf8')) {
|
|
135
|
+
if (ch === '\r' || ch === '\n') {
|
|
136
|
+
cleanup()
|
|
137
|
+
resolve(value)
|
|
138
|
+
return
|
|
139
|
+
}
|
|
140
|
+
if (ch === '\u0003') {
|
|
141
|
+
cleanup()
|
|
142
|
+
reject(new Error('Aborted'))
|
|
143
|
+
return
|
|
144
|
+
}
|
|
145
|
+
if (ch === '\u007f' || ch === '\b') value = value.slice(0, -1)
|
|
146
|
+
else value += ch
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
stdin.on('data', onData)
|
|
150
|
+
})
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// The value for a bare `moi env set KEY`: hidden TTY prompt for humans, piped
|
|
154
|
+
// stdin for scripts (one trailing newline trimmed, so `echo $V | moi env set K`
|
|
155
|
+
// stores exactly $V).
|
|
156
|
+
export async function readSecretValue(key: string): Promise<string> {
|
|
157
|
+
if (process.stdin.isTTY) return readSecretFromTty(`Value for ${key} (hidden): `)
|
|
158
|
+
return (await Bun.stdin.text()).replace(/\r?\n$/, '')
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// ---------------------------------------------------------------------------
|
|
162
|
+
// Server notification after a CLI write
|
|
163
|
+
// ---------------------------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
// Env is frozen at spawn — a running server must reap the widget worker and
|
|
166
|
+
// idle agent sessions for a CLI write to take effect (mirrors PUT /env). Sends
|
|
167
|
+
// `env:changed` over the control port; resolves false when no server is
|
|
168
|
+
// running (fine: the next server start resolves fresh env anyway).
|
|
169
|
+
export function notifyEnvChanged(path: string): Promise<boolean> {
|
|
170
|
+
return new Promise(resolve => {
|
|
171
|
+
let ws: WebSocket
|
|
172
|
+
try {
|
|
173
|
+
ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
|
|
174
|
+
} catch {
|
|
175
|
+
resolve(false)
|
|
176
|
+
return
|
|
177
|
+
}
|
|
178
|
+
const timer = setTimeout(() => {
|
|
179
|
+
try {
|
|
180
|
+
ws.close()
|
|
181
|
+
} catch {}
|
|
182
|
+
resolve(false)
|
|
183
|
+
}, 1500)
|
|
184
|
+
ws.onopen = () => ws.send(JSON.stringify({ type: 'env:changed', path }))
|
|
185
|
+
ws.onmessage = event => {
|
|
186
|
+
clearTimeout(timer)
|
|
187
|
+
ws.close()
|
|
188
|
+
// A malformed reply must still settle the promise — the CLI awaits this.
|
|
189
|
+
try {
|
|
190
|
+
const res: unknown = JSON.parse(String(event.data))
|
|
191
|
+
resolve(typeof res === 'object' && res !== null && (res as { ok?: unknown }).ok === true)
|
|
192
|
+
} catch {
|
|
193
|
+
resolve(false)
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
ws.onerror = () => {
|
|
197
|
+
clearTimeout(timer)
|
|
198
|
+
resolve(false)
|
|
199
|
+
}
|
|
200
|
+
})
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ---------------------------------------------------------------------------
|
|
204
|
+
// `moi env exec`
|
|
205
|
+
// ---------------------------------------------------------------------------
|
|
206
|
+
|
|
207
|
+
// Run `cmd` with the workspace env overlaid on the inherited process env — the
|
|
208
|
+
// workspace resolution wins, so re-resolved values override a stale agent-
|
|
209
|
+
// session snapshot. Returns the child's exit code; 127 when the binary is
|
|
210
|
+
// missing.
|
|
211
|
+
export async function execWithEnv(workspacePath: string, cmd: string[]): Promise<number> {
|
|
212
|
+
const [resolved, dotenvKeys] = await Promise.all([
|
|
213
|
+
resolveWorkspaceEnv(workspacePath),
|
|
214
|
+
discoverDotenvKeys(workspacePath)
|
|
215
|
+
])
|
|
216
|
+
// Bun auto-loads the workspace `.env` into THIS process when the CLI runs
|
|
217
|
+
// from the workspace root, so the inherited env is not trustworthy for
|
|
218
|
+
// workspace keys — scrub them and let the resolution re-add what actually
|
|
219
|
+
// applies (otherwise `inheritDotenv: off` still leaks `.env` values).
|
|
220
|
+
const base: Record<string, string | undefined> = { ...process.env }
|
|
221
|
+
for (const key of dotenvKeys) delete base[key]
|
|
222
|
+
const env = { ...base, ...resolved }
|
|
223
|
+
try {
|
|
224
|
+
const proc = Bun.spawn(cmd, {
|
|
225
|
+
cwd: process.cwd(),
|
|
226
|
+
env,
|
|
227
|
+
stdin: 'inherit',
|
|
228
|
+
stdout: 'inherit',
|
|
229
|
+
stderr: 'inherit'
|
|
230
|
+
})
|
|
231
|
+
return await proc.exited
|
|
232
|
+
} catch (err) {
|
|
233
|
+
const msg = err instanceof Error ? err.message : String(err)
|
|
234
|
+
console.error(pc.red('✗') + ` Could not run ${cmd[0]}: ${msg}`)
|
|
235
|
+
return 127
|
|
236
|
+
}
|
|
237
|
+
}
|
package/server/cli-pc.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Our picocolors instance, with color-enablement we compute ourselves instead
|
|
2
|
+
// of trusting picocolors' auto-detection.
|
|
3
|
+
//
|
|
4
|
+
// picocolors decides `isColorSupported` once, at module-evaluation time, and
|
|
5
|
+
// enables color whenever `CI` is set — regardless of whether stdout is a TTY.
|
|
6
|
+
// That is wrong for us: `moi env` is captured through a pipe by agents and by
|
|
7
|
+
// CI test runners, which must see plain text. We also can't fix it by setting
|
|
8
|
+
// `NO_COLOR` first, because Bun evaluates picocolors early enough that the env
|
|
9
|
+
// mutation doesn't reach it (the `NO_COLOR` trick in `cli-colors.ts` only ever
|
|
10
|
+
// worked for citty, and locally only because the non-TTY path already disabled
|
|
11
|
+
// color when `CI` was absent).
|
|
12
|
+
//
|
|
13
|
+
// So we build colors explicitly: honor `NO_COLOR` / `FORCE_COLOR`, otherwise
|
|
14
|
+
// key off `isTTY` alone. Import this instead of `picocolors` anywhere the CLI
|
|
15
|
+
// colors its own output.
|
|
16
|
+
import { createColors } from 'picocolors'
|
|
17
|
+
|
|
18
|
+
const enabled = !process.env.NO_COLOR && (!!process.env.FORCE_COLOR || !!process.stdout.isTTY)
|
|
19
|
+
|
|
20
|
+
export default createColors(enabled)
|